[Haskell-beginners] What is the best practice for code]

Brent Yorgey byorgey at seas.upenn.edu
Mon Nov 9 20:18:34 EST 2009


On Mon, Nov 09, 2009 at 10:46:19PM +0100, legajid wrote:
>
> {-    Second solution   -}
> futiles2 xx = [(x, y, z) | x <- xx, y <- xx, z <- xx, y < x, z < y]
> f2 = filter (\(x,y,z) -> (x+y+z)==19) (futiles2 nombres )
>
> {-    Third solution  -}
> f3 = filter (\(x,y,z) -> (x+y+z)==19) ((\ xx -> [(x, y, z) | x <- xx, y <- 
> xx, z <- xx, y < x, z < y]) nombres )

I think the second solution is best (the third solution seems hard to
read).  Shorter code is usually better, but avoid long lines that are
hard to scan.

Here's another possibility:

  f4 = filter (\(x,y,z) -> x+y+z == 19)
              [(x,y,z) | x <- [9,8..1], y <- reverse [1..x-1], z <- reverse [1..y-1]]

This way you only generate (x,y,z) where x > y > z, and avoid all the
wasted work of generating triples and then throwing them away.

-Brent


More information about the Beginners mailing list