[Haskell-cafe] multiple computations, same input

Neil Mitchell ndmitchell at gmail.com
Mon Mar 27 19:25:33 EST 2006


> Here would be a better example then.
>     f lst = show (sum (filter (> 1) lst), sum (filter (> 2) lst))

I suspected that you actually wanted to do something "cleverer" with
the list, for the sake of argument, I'm going to change >1 to p1 and
>2 to p2 - to show how this can be done in the general case. With the
specific information you know about >1 vs >2 you can do better, but
this gets across the general point:

f lst = show (sumPairs (>1) (>2) lst)

sumPairs :: (Int -> Bool) -> (Int -> Bool) -> [Int] -> (Int, Int)
sumPairs p1 p2 [] = (0, 0)
sumPairs p1 p2 (x:xs) = (add p1 a, add p2 b)
       (a,b) = sumPairs xs
       add pred value = if pred x then x+value else value

[Untested, something like this should work]

You can actually arrive at this solution entirely be reasoning on the
program, i.e. not coming up with a fresh definition.

The above code essentially follows your imperative pseudo code - I
think its constant space, but I'm not too sure...



More information about the Haskell-Cafe mailing list