【问题标题】:3n+1 implementing with Haskell, compile error3n+1 用 Haskell 实现,编译报错
【发布时间】: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函数中,去掉$,它会导致你显示的错误。

标签: algorithm haskell


【解决方案1】:

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

($) 运算符的绑定比任何其他运算符都没有那么紧密,包括“仅使用空格时获得的普通函数应用程序”。

所以对于$,它会解析为

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

如果你删除它应该按照你的意图解析,这大概是

max (leftValue i j) (rightValue i j)

您可以从错误消息中得到提示,其中提到了“leftValue 的第三个参数”。

When should I use $ (and can it always be replaced with parentheses)? 中有更多关于($) 的信息

【讨论】:

  • 值得注意的是,如果真的需要$,则可以写成max (leftValue i j) $ rightValue i j。或者,您可以使用 leftValue i j `max` rightValue i j 完全避免使用括号,但我觉得这更难阅读
  • 非常感谢,问题解决了。然而出现了新的问题,我认为我应该在 Haskell 中进行更多的练习......:)
猜你喜欢
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多