Consider a recursive branching data structure:
data Tree a = Node (Tree a) (Tree a) | Leaf a
deriving (Show)
You can build a Treewith many identical branches, and this seems to be handled efficiently (at least in the GHC) - for example, by:
maketree :: Integer -> a -> Tree a
maketree 1 value = Leaf value
maketree depth value = let child = maketree (depth-1) value in Node child child
maketree 32 "Hello"will return Tree String, which conceptually contains 4294967295 nodes, but in practice only 32 nodes will be stored in memory, and the body maketreewill be evaluated only 32 times.
However, suppose we are actually trying to use the whole tree in some way - say, count the number of nodes:
count :: Tree a -> Integer
count n = case n of
Leaf _ -> 1
Node a b -> 1 + count a + count b
count (maketree 32 "Hello")will (correctly) be evaluated up to 4294967295, but he will do this by evaluating the body count4294967295 times.
32 "node ", count ( Haskell), node, count 32 .
GHC ( Haskell) ?