[Haskell-beginners] oddsFrom3 function

Doug McIlroy doug at cs.dartmouth.edu
Mon Aug 17 13:17:42 UTC 2015


> > oddsFrom3 :: [Integer]
> > oddsFrom3 = 3 : map (+2) oddsFrom3
> >
> >
> > Thanks for your help.
> 
> Try to expand a few steps of the recursion by hand e.g.:
> 
>    3 : (map (+2) (3 : map (+2) (3 : map (+2) ...)))
> 
> 
> As you can see, the deeper you go more 'map (+2)' are applied to '3'.

Some more ways to describe the program, which may be useful:

As with any recursive function, assume you know the whole series and
then confirm that by verifying the inductive step. In this case
	oddsFrom3          = [3,5,7,9,11,...]
	map (+2) oddsFrom3 = [5,7,9,11,13,...]
voila
	oddsFrom3 = 3 : map (+2) oddsFrom3

Assuming we have the whole series, we see its tail is
computed from the whole by adding 2 to each element.
Notice that we don't actually have to know the values in the
tail in order to write the formula for the tail.

Yet another way to describe the program: the "output"  is taken
as "input". This works because the first element of the output,
namely 3, is provided in advance. Each output element can then 
be computed before it is needed as input.

In an imperative language this would be done so:
	integer oddsFrom3[0:HUGE]
	oddsFrom3[0] := 3
	for i:=1 to HUGE do
		oddsFrom3[i] = oddsFrom3[i-1] + 2


More information about the Beginners mailing list