3n + 1用Haskell实现,编译错误

时间:2014-10-14 19:51:17

标签: algorithm haskell

大家。我是Haskell的新手,并且刚刚实现了'3n + 1'问题。我检查了很多,但类型错误似乎很奇怪,你能帮我找到问题所在吗?

import qualified Data.Vector as V
import qualified Data.Matrix as M

nMax = 1000000

table = V.fromList $ 0 : 1 : [cycleLength x | x <- [2 .. nMax]] where
    cycleLength x = if x' <= nMax then table V.! x' + 1 else cycleLength x' + 1 where 
        x' = if even x then x `div` 2 else 3 * x + 1

sparseTable = M.fromLists $ [] : [[f i j | j <- [0 .. ceiling $ logBase 2 nMax]] | i <- [1 .. nMax]] where
    f i 0 = table V.! i
    f i j = maxValue i j

maxValue i j = max $ (leftValue i j) (rightValue i j) where
    leftValue i j = sparseTable M.! (i, j - 1)
    rightValue i j = sparseTable M.! (i + 2 ^ (j - 1), j - 1)

我使用Vector和Matrix(下载cabal)模块来实现这些功能。我认为第一个函数(表)已被证明没有错误,可能是最后两个函数中的错误,我用它来实现稀疏表算法。

由于我刚刚注册并且现在没有足够的声誉,我只需在此处粘贴错误消息:

[1 of 1] Compiling Main             ( 001.hs, interpreted )

001.hs:14:39:
    Occurs check: cannot construct the infinite type: s0 ~ s0 -> s0
    Relevant bindings include
      leftValue :: Int -> Int -> s0 -> s0 (bound at 001.hs:15:9)
      rightValue :: Int -> Int -> s0 -> s0 (bound at 001.hs:16:9)
      maxValue :: Int -> Int -> s0 -> s0 (bound at 001.hs:14:1)
    In the third argument of ‘leftValue’, namely ‘(rightValue i j)’
    In the second argument of ‘($)’, namely
      ‘(leftValue i j) (rightValue i j)’
Failed, modules loaded: none.

1 个答案:

答案 0 :(得分:4)

问题是$中的max $ (leftValue i j) (rightValue i j)

($)运算符的绑定程度低于任何其他运算符,包括使用空格时获得的正常函数应用程序。

所以使用$,它解析为

max ((leftvalue i j) (rightValue i j))

如果你删除它应该按你的意图解析,这可能是

max (leftValue i j) (rightValue i j)

你可以从错误信息中得到一个暗示,它会谈到leftValue&#34;的第三个参数。

有关When should I use $ (and can it always be replaced with parentheses)?

($)的更多信息