1+ --
2+ -- The Computer Language Benchmarks Game
3+ -- https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
4+ --
5+ -- Contributed by Don Stewart
6+ -- *reset*
7+ --
8+
9+ import System.Environment
10+ import Data.Bits
11+ import Text.Printf
12+
13+ --
14+ -- an artificially strict tree.
15+ --
16+ -- normally you would ensure the branches are lazy, but this benchmark
17+ -- requires strict allocation.
18+ --
19+ data Tree = Nil | Node ! Int ! Tree ! Tree
20+
21+ minN = 4
22+
23+ io s n t = printf " %s of depth %d\t check: %d\n " s n t
24+
25+ main = do
26+ n <- getArgs >>= readIO . head
27+ let maxN = max (minN + 2 ) n
28+ stretchN = maxN + 1
29+
30+ -- stretch memory tree
31+ let c = check (make 0 stretchN)
32+ io " stretch tree" stretchN c
33+
34+ -- allocate a long lived tree
35+ let ! long = make 0 maxN
36+
37+ -- allocate, walk, and deallocate many bottom-up binary trees
38+ let vs = depth minN maxN
39+ mapM_ (\ ((m,d,i)) -> io (show m ++ " \t trees" ) d i) vs
40+
41+ -- confirm the the long-lived binary tree still exists
42+ io " long lived tree" maxN (check long)
43+
44+ -- generate many trees
45+ depth :: Int -> Int -> [(Int ,Int ,Int )]
46+ depth d m
47+ | d <= m = (n,d,sumT d n 0 ) : depth (d+ 2 ) m
48+ | otherwise = []
49+ where n = 1 `shiftL` (m - d + minN)
50+
51+ -- allocate and check lots of trees
52+ sumT :: Int -> Int -> Int -> Int
53+ sumT d 0 t = t
54+ sumT d i t = sumT d (i- 1 ) (t + a)
55+ where a = check (make 0 d)
56+
57+
58+ -- traverse the tree, counting up the nodes
59+ check :: Tree -> Int
60+ check Nil = 0
61+ check (Node i l r) = 1 + check l + check r
62+
63+ -- build a tree
64+ make :: Int -> Int -> Tree
65+ make i 0 = Node i Nil Nil
66+ make i d = Node i (make d d2) (make d2 d2)
67+ where d2 = d- 1
0 commit comments