[Haskell-begin] Alternating sequence

apfelmus apfelmus at quantentunnel.de
Mon Jul 21 10:39:14 EDT 2008


Dirk Markert wrote:
> I am trying to generate the following list:
> 2, 3, 5 -- and then alternating (+2) resp (+4) -- 7, 11, 13, 17, 19, 23
> 
> I came up with the following solution
> 2:3:unfoldr (\(a,b) -> Just (a,(a+b, if b == 2 then 4 else 2))) (5,2)
> 
> Are there easier ways to generate the desired list?

Use a left scan

   result = 2:3:scanl (+) 5 (cycle [2,4])


Regards,
apfelmus



More information about the Beginners mailing list