[Haskell-cafe] Computing lazy and strict list operations at thesame time

Claus Reinke claus.reinke at talk21.com
Wed Sep 27 10:30:00 EDT 2006

> This is a follow-up to a thread from June-July[1].  The question was how to
> write the function
>    initlast :: [a] -> ([a], a)
>    initlast xs = (init xs, last xs)
> so that it can be consumed in fixed space:
>    main = print $ case initlast [0..1000000000] of
>                     (init, last) -> (length init, last)

if space is the main issue, you could try to avoid the sharing
(so that each part of the computation unfolds and throws away
its own copy of the input list):

    initlast :: (()->[a]) -> ([a], a)
    initlast xs = (init (xs ()), last (xs ()))

    main = print $ case initlast (\()->[0..1000000000]) of
                     (init, last) -> (length init, last)


ps. it would occasionally be nice to be able to undo sharing
     instead of having to avoid it, by asking for an independent, 
     equally unevaluated, copy of some expression. that would
     make it easy to write initlast with your original type.

pps. compiling with -O recreates the space problem? (ghc-6.5)

More information about the Haskell-Cafe mailing list