Ackermann very inefficient with Haskell/GHC

后端 未结 7 887
小鲜肉
小鲜肉 2020-12-23 13:58

I try computing Ackermann(4,1) and there\'s a big difference in performance between different languages/compilers. Below are results on my

7条回答
  •  有刺的猬
    2020-12-23 14:11

    This version uses some properties of the ackermann function. It's not equivalent to the other versions, but it's fast :

    ackermann :: Int -> Int -> Int
    ackermann 0 n = n + 1
    ackermann m 0 = ackermann (m - 1) 1
    ackermann 1 n = n + 2
    ackermann 2 n = 2 * n + 3
    ackermann 3 n = 2 ^ (n + 3) - 3
    ackermann m n = ackermann (m - 1) (ackermann m (n - 1))
    

    Edit : And this is a version with memoization , we see that it's easy to memoize a function in haskell, the only change is in the call site :

    import Data.Function.Memoize
    
    ackermann :: Integer -> Integer -> Integer
    ackermann 0 n = n + 1
    ackermann m 0 = ackermann (m - 1) 1
    ackermann 1 n = n + 2
    ackermann 2 n = 2 * n + 3
    ackermann 3 n = 2 ^ (n + 3) - 3
    ackermann m n = ackermann (m - 1) (ackermann m (n - 1))
    
    main :: IO ()
    main = print $ memoize2 ackermann 4 2
    

提交回复
热议问题