Evan Martin (evan) wrote in evan_tech,
Evan Martin
evan
evan_tech

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?)
Tags: haskell
Subscribe
  • Post a new comment

    Error

    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 2 comments