我的以下haskell代码有问题

时间:2019-10-16 21:45:21

标签: haskell functional-programming

我不知道代码有什么问题。我刚刚开始在Haskell中进行编码,为您带来的麻烦深感抱歉。

tobase :: Int -> Int -> [Int]

tobase b x = tobase b (x `quot` b) : [x `mod` b]
tobase b x | x `mod` b == x = [x]
  Couldn't match expected type ‘[Int]’ with actual type ‘Int’
  In the expression: x `mod` b
  In the second argument of ‘(:)’, namely ‘[x `mod` b]’
  In the expression: tobase b (x `quot` b) : [x `mod` b]

1 个答案:

答案 0 :(得分:1)

正如Willem所指出的,该错误的原因是您试图通过“ cons”运算符(:)组合错误类型的值。 该话务员的签名是(:) :: a -> [a] -> [a],而不是(:) :: [a] -> [a] -> [a],这是您的呼叫正在尝试的。

您的tobase函数返回类型[Int],这是传递给:运算符的第一个参数。由于a中的类型变量(:) :: a -> [a] -> [a]在您的调用中具有此[Int]类型,因此编译器期望第二个参数为[[Int]]。但是,您传入的是[x `mod` b]类型的[Int]。 您可以使用:来合并两个列表,而不必使用++

也请注意,函数定义中的模式匹配顺序应颠倒,因为将永远不会达到第二种情况tobase b x | x `mod` b == x = [x]。参见http://learnyouahaskell.com/syntax-in-functions