[Haskell] making inits less strict

John Tromp john.tromp at gmail.com
Mon Apr 7 15:11:16 EDT 2008

The standard definition of inits:

  inits []     =  [[]]
  inits (x:xs) =  [[]] ++ map (x:) (inits xs)

is unnecessarily strict, evaluating its argument
before yielding the initial [] of the result.
An improved version is:

  inits l = [] : case l of []     -> []
                           (x:xs) -> map (x:) inits xs

 This allows one to define for instance
   nats = map length (inits nats)
 which loops for the standard definition.


More information about the Haskell mailing list