Previous Entry Share Next Entry
09:08 am, 17 Jun 05

haskell fun

A short snippet of a haskell session.

I like this definition (which I likely borrowed from somewhere):
let fac n = scanl1 (*) [1..] !! (n-1)

  1. scanl1 produces a list of repeatedly applying the operation to elements in the list. So scanl1 (*) [1..n] provides factorials from 2 to n.
  2. scanl1 (*) [1..], then, is the infinite list of factorials. (Values are only generated once they're asked for...)
  3. And !! is the "get the nth element" operator.

So this code is basically: n factorial is the nth element in the list of all factorials.

It memoizes itself! (I think?)