Reputation: 327
So I've been doing this program which receives a function f
, a number a
and a list b
and it should return a list [a, f(a,b), f(f(a,b),b, ..]
iterating through the list b
and using recursion. Do you guys know how I can optimize my code?
calculate :: (a -> b -> a) -> a -> [b] -> [a]
help :: (a -> b -> a) -> a -> [b] -> [a]
help f a (x:xs) = (f a x) : (calculate f (f a x) xs)
help f a [] = []
calculate f a b = a : (help f a b)
Upvotes: 2
Views: 374
Reputation: 71109
calculate f a b = tail . concatMap (replicate 2) . scanl f a $ b
.
The replicate bit is probably in error. If so, then simply calculate = scanl
.
This translates the code, as the "[a, f(a,b), f(f(a,b),b, ..]
" from the text contradicts it (and it contradicts the text itself, which talks of "iterating through the list b
").
Upvotes: 2