得到类型为Int-> Int而不是Integer,不知道为什么

时间:2019-06-20 16:15:57

标签: haskell fold

我写了这个binarytodecimal-converter,得到了一个编译器错误,我不知道它来自哪里。

binaryToInteger :: [Bool] -> Integer
binaryToInteger (x:xs) = foldr (\x y z -> (fromEnum x) * 2^y + z) 0 [0..length (x:xs)] 

实际上,程序应返回二进制数的十进制结果。 给出的例子: binaryToInteger [True,True,False] == 1 (2 ^ 2)+ 1 *(2 ^ 1)+ 0 *(2 ^ 0)== 6 *

我的错误消息如下: 无法匹配预期的类型Integer' with actual type Int-> Int'

  * Probable cause: `foldr' is applied to too few arguments
  In the expression:
    foldr (\ x y z -> (fromEnum x) * 2 ^ y + z) 0 [0 .. length (x : xs)]
  In an equation for `binaryToInteger':
      binaryToInteger (x : xs)
        = foldr
            (\ x y z -> (fromEnum x) * 2 ^ y + z) 0 [0 .. length (x : xs)]

1 个答案:

答案 0 :(得分:1)

算法如下:

  • 您从a = 0开始(“ a”代表“累加器”)
  • 对于True:双击a并在其中添加1
  • 错误:只需加倍

示例:[True,False,True]

  • a = 0
  • True => a变为1(因为0 * 2 +1 = 1)
  • False => a变为2(因为1 * 2 = 2)
  • True => a变为5(因为2 * 2 +1 = 5)
  • a = 5是解决方案

在Haskell代码中:

import Data.List (foldl')

binaryToInteger :: [Bool] -> Integer
binaryToInteger xs = foldl' f 0 xs where
    f a True  = a * 2 + 1
    f a False = a * 2

请勿使用幂运算(^),因为它会降低性能。我使用了左折,因为它更适合此问题。函数foldl'具有严格的附加优点,因此不会引起空间泄漏。

相关问题