[Haskell-beginners] code critique

Arlen Cuss celtic at sairyx.org
Wed Jul 27 02:31:15 CEST 2011


27/07/2011 9:47 AM, Jeff Lasslett kirjutas:
> Also, if I understand correctly, solutions 1 & 2 will only produce one
> pair, whereas solution 3 (based on list comprehensions) will produce
> all pairs that sum to the total.

Correct, though it discards them in the end and only returns a Bool.
That it does collect all the answers (before discarding) is probably why
it has such a memory hit.

> sumCheck1 _     []     _  = Nothing
> sumCheck1 total (x:xs) ys = if total' == Nothing
>                           then sumCheck total xs ys
>                           else return (x,(ys!!(fromJust total')))
>                           where total' = elemIndex (total-x) ys
>
> sumCheck2 total (x:xs) ys =
>    let diff = total - x
>    in if elem diff ys
>       then Just (x,diff)
>       else sumCheck total xs ys
>
> sumCheck3 i as bs = not $ null [(x,y) | x <- as, y <- bs, x+y==i ]



More information about the Beginners mailing list