# What is the best practice for code] Classic List Threaded 4 messages Open this post in threaded view
|

## What is the best practice for code]

 Hello, i wanted to write a program that searches for all combinations of some numbers, the sum of which is a given value. So, i started writing my program, creating a function for each separate phase : creating list of triples, selecting valuable ones, filtering the result. Looking at my code, i've reduced it several ways; the last version holds on one single line of code. Please, from the 3 versions i established, which one is " better"? What are the criterias of a "good" code ? What about using many anonymous functions? I think there are other solutions than those i propose. Following is my code {-    First solution     -} nombres=[9,8..1] -- all combinations ftoutes xx = [(x, y, z) | x <- xx, y <- xx, z <- xx] -- keep valuable ones futiles xyz = [(x, y, z) | (x,y,z) <- xyz, y < x, z < y ] -- filter f_flt (x,y, z) = (x+y+z) == 19 -- final result f = filter (f_flt) (futiles (ftoutes nombres )) {-    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 ) Thanks for your advice Didier.
Open this post in threaded view
|

## What is the best practice for code]

 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