fibonacci memoization speed tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
{- benchmark of a bunch of memoization strategies for fibonacci
   "Fibonacci is the E. Coli of Haskell optimization experiments"
            (misquoting someone)

  Author: solrize, June 24, 2012

  Inspiration:
  http://stackoverflow.com/questions/4980102/how-does-data-memocombinators-work

  Output on 2.5 ghz Intel Core 2, GHC 7.03 with -O2:
    name       usec    (N = 50000)
    MT        484926
    linear    292955
    array     180973
    conal     534918
    luqui     939857
    direct     94985
    intmap    371944
    ugly      528920
    STArray   327949
-}
{-# LANGUAGE BangPatterns, RankNTypes #-}

module Main (main) where

import System.CPUTime
import Data.Array
import qualified Data.MemoTrie as Conal
import qualified Data.MemoCombinators as Luqui
import GHC.IO
import Text.Printf
import qualified Data.IntMap as IM
import Control.Monad.ST
import Data.STRef
import qualified Data.MemoUgly as Ugly
import Data.Array.ST
import Data.Maybe (fromJust)

testValue = 50000

type Fibn = Int -> Integer

data MTree a r = MTree {
  v0 :: r
  , v1 :: r
  , m0 ::  MTree a r
  , m1 ::  MTree a r
  } deriving Show

memo :: Integral a => (a -> r) -> (a -> r)
memo f = tfind (r 1 0)
      where
        r p k = MTree { v0 = f k, v1 = f (k+p)
                      , m0 = r (p*2) k, m1 = r (p*2) (k+p)
                      }

        tfind (MTree {v0=v0, v1=v1, m0=m0, m1=m1}) k
          | k < 0 = error "k<0 is left as an exercise"
          | k == 0 = v0
          | k == 1 = v1
          | even k = tfind m0 k2
          | odd k = tfind m1 k2
            where
              k2 = k`div`2

-- direct tail recursion
fibDirect :: Fibn
fibDirect n = go n 0 1
  where
    go 0 a b = a
    go !n !a !b = go (n-1) b (a+b)

-- MTree infinite tree memoization
fibMT :: Fibn
fibMT = memo fib0
  where
    fib0 0 = 0
    fib0 1 = 1
    fib0 n = fibMT (n-1) + fibMT (n-2)

-- reference linear implementation
fibLinear :: Fibn
fibLinear n = fibLinear' 0 1 !! n
  where
    fibLinear' m n = m : fibLinear' n (m+n)

-- array-based memoization
memarray = array (0,testValue) [(i,fibArray i)|i<-[0..testValue]]
fibArray :: Fibn
fibArray 0 = 0
fibArray 1 = 1
fibArray n  = memarray ! (n-1) + memarray ! (n-2)

-- Conal Eliot's MemoTrie
fibConal :: Fibn
fibConal = Conal.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibConal (n-1) + fibConal (n-2)
    
-- Luqui's memo combinators
fibLuqui :: Fibn
fibLuqui = Luqui.integral fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibLuqui (n-1) + fibLuqui (n-2)

-- imperative-ish manual intmap memoization
fibIntMap :: Fibn
fibIntMap n = runST $ do
  xmemo <- newSTRef $ IM.fromList [(0,0),(1,1)]
  let fibx n = do
        v <- readSTRef xmemo
        case IM.lookup n v of
          Just x -> return x
          Nothing -> do
            a <- fibx (n-1)
            b <- fibx (n-2)
            let c = a + b
            modifySTRef xmemo (IM.insert n c)
            return c
  fibx n
  
-- Uglymemo (uses unsafePerformIO)
fibUgly :: Fibn
fibUgly = Ugly.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibUgly (n-1) + fibUgly (n-2)

-- mutable array per jmcarthur's suggestion of a hash table
fibSTArray :: Fibn
fibSTArray n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) Nothing
               :: ST s (STArray s Int (Maybe Integer))
      writeArray xmemo 0 (Just 0)
      writeArray xmemo 1 (Just 1)
      let fibr k = do
            r <- readArray xmemo k
            case r of
              Just x -> return x
              Nothing -> do
                a <- fibr (k-1)
                b <- fibr (k-2)
                let c = a+b
                writeArray xmemo k (Just c)
                return c
      fibr n
{-
test = a1 == a2 && a2 == a3 where
    a1 = fibMT k
    a2 = fibLinear k
    a3 = fibArray k
    k = 12345
-}


main = do
  putStrLn $ "name       usec    (N = " ++ show testValue ++ ")"
  p "MT" fibMT
  p "linear" fibLinear
  p "array" fibArray
  p "conal" fibConal
  p "luqui" fibLuqui
  p "direct" fibDirect
  p "intmap" fibIntMap
  p "ugly" fibUgly
  p "STArray" fibSTArray

  where
    p label f = do
      t0 <- getCPUTime
      a <- evaluate (f testValue)
      t1 <- getCPUTime
      let dt = (t1-t0)`div`(10^6) -- microseconds
      printf "%-8s %7d\n" label dt
50:23: Warning: Redundant bracket
Found:
(a -> r) -> (a -> r)
Why not:
(a -> r) -> a -> r

fibonacci memoization speed tests (more timings added)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
{- benchmark of a bunch of memoization strategies for fibonacci
   "Fibonacci is the E. Coli of Haskell optimization experiments"
            (misquoting someone)

  Author: solrize, June 24, 2012

  Inspiration:
  http://stackoverflow.com/questions/4980102/how-does-data-memocombinators-work

  Output on 2.5 ghz Intel Core 2, GHC 7.03 with -O2:
    name       usec    (N = 50000)
    MT        473928
    linear    293956
    array     182971
    conal     540918
    luqui     940858
    direct     94986
    intmap    372943
    ugly      530919
    STArray   324950
    STArray2  435934

  Also measured C++ counterparts of direct and STArray2,
  giving 40000 and 160000 microseconds respectively.
-}
{-# LANGUAGE BangPatterns, RankNTypes #-}

module Main (main) where

import System.CPUTime
import Data.Array
import qualified Data.MemoTrie as Conal
import qualified Data.MemoCombinators as Luqui
import GHC.IO
import Text.Printf
import qualified Data.IntMap as IM
import Control.Monad.ST
import Data.STRef
import qualified Data.MemoUgly as Ugly
import Data.Array.ST
import Data.Maybe (fromJust)

testValue = 50000

type Fibn = Int -> Integer

data MTree a r = MTree {
  v0 :: r
  , v1 :: r
  , m0 ::  MTree a r
  , m1 ::  MTree a r
  } deriving Show

memo :: Integral a => (a -> r) -> (a -> r)
memo f = tfind (r 1 0)
      where
        r p k = MTree { v0 = f k, v1 = f (k+p)
                      , m0 = r (p*2) k, m1 = r (p*2) (k+p)
                      }

        tfind (MTree {v0=v0, v1=v1, m0=m0, m1=m1}) k
          | k < 0 = error "k<0 is left as an exercise"
          | k == 0 = v0
          | k == 1 = v1
          | even k = tfind m0 k2
          | odd k = tfind m1 k2
            where
              k2 = k`div`2

-- direct tail recursion
fibDirect :: Fibn
fibDirect n = go n 0 1
  where
    go 0 a b = a
    go !n !a !b = go (n-1) b (a+b)

-- MTree infinite tree memoization
fibMT :: Fibn
fibMT = memo fib0
  where
    fib0 0 = 0
    fib0 1 = 1
    fib0 n = fibMT (n-1) + fibMT (n-2)

-- reference linear implementation
fibLinear :: Fibn
fibLinear n = fibLinear' 0 1 !! n
  where
    fibLinear' m n = m : fibLinear' n (m+n)

-- array-based memoization
memarray = array (0,testValue) [(i,fibArray i)|i<-[0..testValue]]
fibArray :: Fibn
fibArray 0 = 0
fibArray 1 = 1
fibArray n  = memarray ! (n-1) + memarray ! (n-2)

-- Conal Eliot's MemoTrie
fibConal :: Fibn
fibConal = Conal.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibConal (n-1) + fibConal (n-2)
    
-- Luqui's memo combinators
fibLuqui :: Fibn
fibLuqui = Luqui.integral fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibLuqui (n-1) + fibLuqui (n-2)

-- imperative-ish manual intmap memoization
fibIntMap :: Fibn
fibIntMap n = runST $ do
  xmemo <- newSTRef $ IM.fromList [(0,0),(1,1)]
  let fibx n = do
        v <- readSTRef xmemo
        case IM.lookup n v of
          Just x -> return x
          Nothing -> do
            a <- fibx (n-1)
            b <- fibx (n-2)
            let c = a + b
            modifySTRef xmemo (IM.insert n c)
            return c
  fibx n
  
-- Uglymemo (uses unsafePerformIO)
fibUgly :: Fibn
fibUgly = Ugly.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibUgly (n-1) + fibUgly (n-2)

-- mutable array per jmcarthur's suggestion of a hash table
fibSTArray :: Fibn
fibSTArray n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) Nothing
               :: ST s (STArray s Int (Maybe Integer))
      writeArray xmemo 0 (Just 0)
      writeArray xmemo 1 (Just 1)
      let fibr k = do
            r <- readArray xmemo k
            case r of
              Just x -> return x
              Nothing -> do
                a <- fibr (k-1)
                b <- fibr (k-2)
                let c = a+b
                writeArray xmemo k (Just c)
                return c
      fibr n

-- similar to above, but use -1 as a sentinel in an
-- an Integer array, instead of array of Maybe Integer.
-- This seems to actually be slower than the Maybe version.
fibSTArray2 :: Fibn
fibSTArray2 n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) (-1)
               :: ST s (STArray s Int Integer)
      writeArray xmemo 0 0
      writeArray xmemo 1 1
      let fibr k = do
            r <- readArray xmemo k
            if r >= 0 then return r
              else do {
              a <- fibr (k-1)
              ; b <- fibr (k-2)
              ; let c = a+b
              ; writeArray xmemo k c
              ; return c
              }
      fibr n

{-
test = a1 == a2 && a2 == a3 where
    a1 = fibMT k
    a2 = fibLinear k
    a3 = fibArray k
    k = 12345
-}


main = do
  putStrLn $ "name       usec    (N = " ++ show testValue ++ ")"
  p "MT" fibMT
  p "linear" fibLinear
  p "array" fibArray
  p "conal" fibConal
  p "luqui" fibLuqui
  p "direct" fibDirect
  p "intmap" fibIntMap
  p "ugly" fibUgly
  p "STArray" fibSTArray
  p "STArray2" fibSTArray2
  where
    p label f = do
      t0 <- getCPUTime
      a <- evaluate (f testValue)
      t1 <- getCPUTime
      let dt = (t1-t0)`div`(10^6) -- microseconds
      printf "%-8s %7d\n" label dt
152:17: Warning: Reduce duplication
Found:
a <- fibr (k - 1)
b <- fibr (k - 2)
let c = a + b
Why not:
Combine with /tmp/70424.hs:174:15
54:23: Warning: Redundant bracket
Found:
(a -> r) -> (a -> r)
Why not:
(a -> r) -> a -> r

fibonacci memoization speed tests (annotation)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
{- benchmark of a bunch of memoization strategies for fibonacci
   "Fibonacci is the E. Coli of Haskell optimization experiments"
            (misquoting someone)

  Author: solrize, June 24, 2012

  Inspiration:
  http://stackoverflow.com/questions/4980102/how-does-data-memocombinators-work

  Output on 2.5 ghz Intel Core 2, GHC 7.03 with -O2:
        name       usec    (N = 50000)
    name       usec    (N = 50000)
    memo1     449932
    m2        356945
    linear    140978
    array     183972
    conal     594910
    luqui    1029844
    direct     93985
    intmap    356945
    ugly      468929
    STArray   229965
    STArray2  455930

  Also measured C++ counterparts of direct and STArray2,
  giving 40000 and 160000 microseconds respectively.
-}
{-# LANGUAGE BangPatterns, RankNTypes #-}

module Main (main) where

import System.CPUTime
import Data.Array
import qualified Data.MemoTrie as Conal
import qualified Data.MemoCombinators as Luqui
import GHC.IO
import Text.Printf
import qualified Data.IntMap as IM
import Control.Monad.ST
import Data.STRef
import qualified Data.MemoUgly as Ugly
import Data.Array.ST
import Data.Maybe (fromJust)

testValue = 50000

type Fibn = Int -> Integer
    
-- direct tail recursion
fibDirect :: Fibn
fibDirect n = go n 0 1
  where
    go 0 a b = a
    go !n !a !b = go (n-1) b (a+b)

-- MTree infinite tree memoization
data MTree a r = MTree {
  v0 :: r
  , v1 :: r
  , m0 ::  MTree a r
  , m1 ::  MTree a r
  } deriving Show

memo1 :: Integral a => (a -> r) -> (a -> r)
memo1 f = tfind (r 1 0)
  where
    r p k = MTree { v0 = f k, v1 = f (k+p)
                  , m0 = r (p*2) k, m1 = r (p*2) (k+p)
                  }
    
    tfind (MTree {v0=v0, v1=v1, m0=m0, m1=m1}) k
      | k < 0 = error "k<0 is left as an exercise"
      | k == 0 = v0
      | k == 1 = v1
      | even k = tfind m0 k2
      | odd k = tfind m1 k2
        where
          k2 = k`quot`2

fibMT :: Fibn
fibMT = memo1 fib0
  where
    fib0 0 = 0
    fib0 1 = 1
    fib0 n = fibMT (n-1) + fibMT (n-2)

-- alternate infinite tree memoization
data Memo2 a = Memo2 { m2e :: Memo2 a -- k*2
                     , m2o :: Memo2 a -- k*2 + 1
                     , m2v :: a       -- value
                     }
memo2 :: Integral a => (a -> r) -> a -> r
memo2 f = find2 (r 0)
  where
    r k = Memo2 { m2e=r (2*k), m2o=r (2*k+1), m2v=f k }
    find2 :: Integral a => Memo2 r -> a -> r
    find2 m k
      | k < 0 = error "k < 0 not handled"
      | otherwise = m2v (find2' m k)
    find2' :: Integral a => Memo2 r -> a -> Memo2 r
    find2' m k
      | k == 0 = m
      | odd k = m2o k2
      | otherwise = m2e k2
        where
          k2 = find2' m (k`quot`2)

fibm2 :: Fibn
fibm2 = memo2 fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr k = fibm2 (k-1) + fibm2 (k-2)

-- reference linear implementation
fibLinear :: Fibn
fibLinear n = fibLinear' 0 1 !! n
  where
    fibLinear' m n = m : fibLinear' n (m+n)

-- array-based memoization
memarray = array (0,testValue) [(i,fibArray i)|i<-[0..testValue]]
fibArray :: Fibn
fibArray 0 = 0
fibArray 1 = 1
fibArray n  = memarray ! (n-1) + memarray ! (n-2)

-- Conal Eliot's MemoTrie
fibConal :: Fibn
fibConal = Conal.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibConal (n-1) + fibConal (n-2)
    
-- Luqui's memo combinators
fibLuqui :: Fibn
fibLuqui = Luqui.integral fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibLuqui (n-1) + fibLuqui (n-2)

-- imperative-ish manual intmap memoization
fibIntMap :: Fibn
fibIntMap n = runST $ do
  xmemo <- newSTRef $ IM.fromList [(0,0),(1,1)]
  let fibx n = do
        v <- readSTRef xmemo
        case IM.lookup n v of
          Just x -> return x
          Nothing -> do
            a <- fibx (n-1)
            b <- fibx (n-2)
            let c = a + b
            modifySTRef xmemo (IM.insert n c)
            return c
  fibx n
  
-- Uglymemo (uses unsafePerformIO)
fibUgly :: Fibn
fibUgly = Ugly.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibUgly (n-1) + fibUgly (n-2)

-- mutable array per jmcarthur's suggestion of a hash table
fibSTArray :: Fibn
fibSTArray n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) Nothing
               :: ST s (STArray s Int (Maybe Integer))
      writeArray xmemo 0 (Just 0)
      writeArray xmemo 1 (Just 1)
      let fibr k = do
            r <- readArray xmemo k
            case r of
              Just x -> return x
              Nothing -> do
                a <- fibr (k-1)
                b <- fibr (k-2)
                let c = a+b
                writeArray xmemo k (Just c)
                return c
      fibr n

-- similar to above, but use -1 as a sentinel in an
-- an Integer array, instead of array of Maybe Integer.
-- This seems to actually be slower than the Maybe version.
fibSTArray2 :: Fibn
fibSTArray2 n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) (-1)
               :: ST s (STArray s Int Integer)
      writeArray xmemo 0 0
      writeArray xmemo 1 1
      let fibr k = do
            r <- readArray xmemo k
            if r >= 0 then return r
              else do {
              a <- fibr (k-1)
              ; b <- fibr (k-2)
              ; let c = a+b
              ; writeArray xmemo k c
              ; return c
              }
      fibr n

{-
test = a1 == a2 && a2 == a3 where
    a1 = fibMT k
    a2 = fibLinear k
    a3 = fibArray k
    k = 12345
-}


main = do
  putStrLn $ "name       usec    (N = " ++ show testValue ++ ")"
  p "memo1" fibMT
  p "m2" fibm2
  p "linear" fibLinear
  p "array" fibArray
  p "conal" fibConal
  p "luqui" fibLuqui
  p "direct" fibDirect
  p "intmap" fibIntMap
  p "ugly" fibUgly
  p "STArray" fibSTArray
  p "STArray2" fibSTArray2
  where
    p label f = do
      t0 <- getCPUTime
      a <- evaluate (f testValue)
      t1 <- getCPUTime
      let dt = (t1-t0)`div`(10^6) -- microseconds
      printf "%-8s %7d\n" label dt
182:17: Warning: Reduce duplication
Found:
a <- fibr (k - 1)
b <- fibr (k - 2)
let c = a + b
Why not:
Combine with /tmp/70506.hs:204:15
64:24: Warning: Redundant bracket
Found:
(a -> r) -> (a -> r)
Why not:
(a -> r) -> a -> r

fibonacci memoization speed tests (annotation)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
{- benchmark of a bunch of memoization strategies for fibonacci
   "Fibonacci is the E. Coli of Haskell optimization experiments"
            (misquoting someone)

  Author: solrize, June 24, 2012
  URL: http://hpaste.org/70413 (see annotations for updates)

  Inspiration:
  http://stackoverflow.com/questions/4980102/how-does-data-memocombinators-work

  Output on 2.5 ghz Intel Core 2, GHC 7.03 with -O2:
     name           usec (N = 50000)
    memo1               448931
    memo2               346948
    linear              139979
    array               181972
    memoTrie            589911
    memoCombinators    1030843
    direct               93986
    intmap              348946
    ugly                467929
    STArray             223966
    STArray2            452931

  Also measured C++ counterparts of direct and STArray2,
  giving 40000 and 160000 microseconds respectively.
-}
{-# LANGUAGE BangPatterns #-}

module Main (main) where

import System.CPUTime
import Data.Array
import qualified Data.MemoTrie as MemoTrie
import qualified Data.MemoCombinators as MemoCombinators
import GHC.IO
import Text.Printf
import qualified Data.IntMap as IM
import Control.Monad.ST
import Data.STRef
import qualified Data.MemoUgly as Ugly
import Data.Array.ST
import Data.Maybe (fromJust)

testValue = 50000

type Fibn = Int -> Integer
    
-- direct tail recursion
fibDirect :: Fibn
fibDirect n = go n 0 1
  where
    go 0 a b = a
    go !n !a !b = go (n-1) b (a+b)

-- MTree infinite tree memoization
data MTree a r = MTree {
  v0 :: r
  , v1 :: r
  , m0 ::  MTree a r
  , m1 ::  MTree a r
  } deriving Show

memo1 :: Integral a => (a -> r) -> (a -> r)
memo1 f = tfind (r 1 0)
  where
    r p k = MTree { v0 = f k, v1 = f (k+p)
                  , m0 = r (p*2) k, m1 = r (p*2) (k+p)
                  }
    
    tfind (MTree {v0=v0, v1=v1, m0=m0, m1=m1}) k
      | k < 0 = error "k<0 is left as an exercise"
      | k == 0 = v0
      | k == 1 = v1
      | even k = tfind m0 k2
      | odd k = tfind m1 k2
        where
          k2 = k`quot`2

fibMT :: Fibn
fibMT = memo1 fib0
  where
    fib0 0 = 0
    fib0 1 = 1
    fib0 n = fibMT (n-1) + fibMT (n-2)

-- alternate infinite tree memoization
data Memo2 a = Memo2 { m2e :: Memo2 a -- k*2
                     , m2o :: Memo2 a -- k*2 + 1
                     , m2v :: a       -- value
                     }
memo2 :: Integral a => (a -> r) -> a -> r
memo2 f = find2 (r 0)
  where
    r k = Memo2 { m2e=r (2*k), m2o=r (2*k+1), m2v=f k }
    find2 :: Integral a => Memo2 r -> a -> r
    find2 m k
      | k < 0 = error "k < 0 not handled"
      | otherwise = m2v (find2' m k)
    find2' :: Integral a => Memo2 r -> a -> Memo2 r
    find2' m k
      | k == 0 = m
      | odd k = m2o k2
      | otherwise = m2e k2
        where
          k2 = find2' m (k`quot`2)

fibm2 :: Fibn
fibm2 = memo2 fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr k = fibm2 (k-1) + fibm2 (k-2)

-- reference linear implementation
fibLinear :: Fibn
fibLinear n = fibLinear' 0 1 !! n
  where
    fibLinear' m n = m : fibLinear' n (m+n)

-- array-based memoization
memarray = array (0,testValue) [(i,fibArray i)|i<-[0..testValue]]
fibArray :: Fibn
fibArray 0 = 0
fibArray 1 = 1
fibArray n  = memarray ! (n-1) + memarray ! (n-2)

-- Conal Eliot's MemoTrie
fibMemoTrie :: Fibn
fibMemoTrie = MemoTrie.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibMemoTrie (n-1) + fibMemoTrie (n-2)
    
-- Luqui's memo combinators
fibMemoCombinators :: Fibn
fibMemoCombinators = MemoCombinators.integral fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibMemoCombinators (n-1) + fibMemoCombinators (n-2)

-- imperative-ish manual intmap memoization
fibIntMap :: Fibn
fibIntMap n = runST $ do
  xmemo <- newSTRef $ IM.fromList [(0,0),(1,1)]
  let fibx n = do
        v <- readSTRef xmemo
        case IM.lookup n v of
          Just x -> return x
          Nothing -> do
            a <- fibx (n-1)
            b <- fibx (n-2)
            let c = a + b
            modifySTRef xmemo (IM.insert n c)
            return c
  fibx n
  
-- Uglymemo (uses unsafePerformIO)
fibUgly :: Fibn
fibUgly = Ugly.memo fibr
  where
    fibr 0 = 0
    fibr 1 = 1
    fibr n = fibUgly (n-1) + fibUgly (n-2)

-- mutable array per jmcarthur's suggestion of a hash table
fibSTArray :: Fibn
fibSTArray n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) Nothing
               :: ST s (STArray s Int (Maybe Integer))
      writeArray xmemo 0 (Just 0)
      writeArray xmemo 1 (Just 1)
      let fibr k = do
            r <- readArray xmemo k
            case r of
              Just x -> return x
              Nothing -> do
                a <- fibr (k-1)
                b <- fibr (k-2)
                let c = a+b
                writeArray xmemo k (Just c)
                return c
      fibr n

-- similar to above, but use -1 as a sentinel in an
-- an Integer array, instead of array of Maybe Integer.
-- This seems to actually be slower than the Maybe version.
fibSTArray2 :: Fibn
fibSTArray2 n = imemo
  where
    imemo = runST $ do
      xmemo <- newArray (0, testValue) (-1)
               :: ST s (STArray s Int Integer)
      writeArray xmemo 0 0
      writeArray xmemo 1 1
      let fibr k = do
            r <- readArray xmemo k
            if r >= 0 then return r
              else do {
              a <- fibr (k-1)
              ; b <- fibr (k-2)
              ; let c = a+b
              ; writeArray xmemo k c
              ; return c
              }
      fibr n

{-
test = a1 == a2 && a2 == a3 where
    a1 = fibMT k
    a2 = fibLinear k
    a3 = fibArray k
    k = 12345
-}


main = do
  putStrLn $ "     name           usec (N = " ++ show testValue ++ ")"
  p "memo1" fibMT
  p "memo2" fibm2
  p "linear" fibLinear
  p "array" fibArray
  p "memoTrie" fibMemoTrie
  p "memoCombinators" fibMemoCombinators
  p "direct" fibDirect
  p "intmap" fibIntMap
  p "ugly" fibUgly
  p "STArray" fibSTArray
  p "STArray2" fibSTArray2
  where
    p label f = do
      t0 <- getCPUTime
      a <- evaluate (f testValue)
      t1 <- getCPUTime
      let dt = (t1-t0)`div`(10^6) -- microseconds
      printf "    %-18s %7d\n" label dt
182:17: Warning: Reduce duplication
Found:
a <- fibr (k - 1)
b <- fibr (k - 2)
let c = a + b
Why not:
Combine with /tmp/70844.hs:204:15
64:24: Warning: Redundant bracket
Found:
(a -> r) -> (a -> r)
Why not:
(a -> r) -> a -> r