【发布时间】:2014-10-14 19:51:16
【问题描述】:
每个人。我是 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.
【问题讨论】:
-
在
maxValue函数中,去掉$,它会导致你显示的错误。