[Haskell-cafe] How to construct a lazy list of eagerly-evaluated items?

Vladimir Ch. cctv.star at gmail.com
Sat May 22 19:10:54 EDT 2010


I'm using Project Euler to learn Haskell. In particular, I'm writing a
program for Problem 18:
http://projecteuler.net/index.php?section=problems&id=18. As a solution, I'm
constructing a list, containing maximum sums of values on a path from top of
the triangle to a given item. In this list, item value equals value of an
item from an input list plus maximum of values of the "top neighbours",
taken from the same list we're constructing. Here's the program:

BEGIN CODE

triangle18 =  [75...etc - definition of the input triangle

sqrti n = truncate (sqrt (fromIntegral n))

-- returns true if a number is an exact square
isSquare n = n == r * r
             where r = sqrti n

-- returns true if a number is a triangular numberx
isTriangular n = isSquare (8 * n + 1)

-- returns index of the top-right neighbour
prevRight i = i - (sqrti (8 * i + 1) - 1) `div` 2

-- returns index of the top-left neighbour
prevLeft i = prevRight i - 1

-- returns the list of top neighbours (at most 2)
prev i
  | i == 0               = []
  | isTriangular i       = [prevRight i]
  | isTriangular (i + 1) = [prevLeft i]
  | otherwise            = [prevLeft i, prevRight i]


-- returns the list of 'path sums' for a given list of input numbers
maxPaths vals@(v:vs) = v : zipWith mpath [1..] vs
                       where mpath i val = val + maximum [(maxPaths vals) !!
pi| pi <- prev i]

result18 = maximum (maxPaths triangle18)

END CODE

The program works, but consumes obscene amount of memory. I suspect that
it's because of lazy evaluation of items in the list we're constructing (and
also using during construction). How can I force eager evaluation of items,
put into the list?

Any other comments and suggestions are also very welcome.

I know index-based item lookup in a list is not efficient, but I'll take
care of this later (I don't know much about arrays yet). For now, I'm more
concerned with the memory usage.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100522/5b698b79/attachment.html


More information about the Haskell-Cafe mailing list