Friday, 15 June 2012

Infinitely lazy factorial in Haskell -



Infinitely lazy factorial in Haskell -

in similar fashion fibonacci series may generated follows,

fibs :: [integer] fibs = 1 : 1 : zipwith (+) fibs (tail fibs)

how define series factorial.

update

embarrassingly enough, tried quite before adding question,

prelude> allow factorial = 2 : 6 : zipwith(*) factorial (tail factorial) prelude> take 5 factorial [2,6,12,72,864]

indeed numbers in tail not successive values, start with.

lets take step , remember lazy version comes from:

fib 0 = 1 fib 1 = 1 fib n = fib (n-1) + fib (n-2)

we can define factorial similarly:

factorial 0 = 1 factorial n = factorial (n - 1) * n

as can see, our zipping operation (*), , sec list won't sublist of factorials, instead [x..] appropriate x:

factorials = 1 : zipwith (*) factorials [x..]

what value should x be? well, sec element should 1 = 1 * 1, it's 1, naturally:

factorials = 1 : zipwith (*) factorials [1..]

note need give first element, since don't utilize tail or similar. can see, effort correct. used wrong values left hand side:

prelude> allow factorial = 2 : 6 : zipwith (*) [4..] (tail factorial) prelude> take 10 $ factorial [2,6,24,120,720,5040,40320,362880,3628800,39916800]

remark: factorial sequence 0!, 1!, 2!, ..., if want oeis compliant start [1,1,...].

haskell lazy-evaluation factorial

No comments:

Post a Comment