[Haskell-begin] Alternating sequence

Kurt Hutchinson kelanslists at gmail.com
Mon Jul 21 10:26:23 EDT 2008


On Mon, Jul 21, 2008 at 9:34 AM, Dirk Markert <dirk.markert at gmail.com> 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?


So you've got the beginnings of an infinite list, and a rule to modify
that to generate new elements. How about turning that rule into a list
of its own, and then combining them?

  rule = cycle [ 2, 4 ]  -- this will give an infinite list of 2's and 4's

Combining two lists is usually done with 'zip'. But in this case, we
don't just want tuples, we want the sum of each pair. You can combine
lists with a function by using 'zipWith'. Start at the point where the
rule kicks in.

  rest = 5 : zipWith (+) rest rule

Now just tack on your first elements.

  list = 2 : 3 : rest

Here it is all in one place:

  list = 2 : 3 : rest
    where
    rule = cycle [ 2, 4 ]
    rest = 5 : zipWith (+) rest rule

Kurt


More information about the Beginners mailing list