[Haskell-cafe] turning an imperative loop to Haskell

Jules Bean jules at jellybean.co.uk
Thu Sep 6 10:12:49 EDT 2007


Axel Gerstenberger wrote:
> Thanks to all of you. The suggestions work like a charm. Very nice.
> 
> I still need to digest the advices, but have already one further 
> question: How would I compute the new value based on the 2 (or even 
> more) last values instead of only the last one?
> 
> [ 2, 3 , f 3 2, f((f 3 2) 3), f ( f((f 3 2) 3)  f 3 2)), ...]


You define the whole list recursively. This is commonly shown as an 
example for the fibonacci numbers; yours is similar:

axelg = 2 : 3 : zipWith f (tail axelg) axelg

...indeed, in the case where f = (+) this *is* the fibonacci sequence:

Prelude> let axelg = 2 : 3 : zipWith (+) (tail axelg) axelg in take 10 axelg
[2,3,5,8,13,21,34,55,89,144]

Jules



More information about the Haskell-Cafe mailing list