我学习Haskell并坚持努力理解类型系统。

我试图写它返回该系列的半或三加一'的长度为输入的函数。这是我尝试在功能,使用递归的方法(该功能是有效的积分仅输入):

hotpo :: (Integral a) => a->a
hotpo n = hotpoHelper n 1

hotpoHelper:: (Integral a) => a->a->a
hotpoHelper 1 n = n
hotpoHelper num count
    | even num = hotpoHelper (truncate (num/2)) (count+1)
    | otherwise = hotpoHelper (3*num+1) (count+1)

下面是我得到的错误,当我尝试加载该文件在GHC 6.12.3

test.hs:8:30:
    Could not deduce (RealFrac a) from the context (Integral a)
      arising from a use of `truncate' at test.hs:8:30-45
    Possible fix:
      add (RealFrac a) to the context of
        the type signature for `hotpoHelper'
    In the first argument of `hotpoHelper', namely
        `(truncate (num / 2))'
    In the expression: hotpoHelper (truncate (num / 2)) (count + 1)
    In the definition of `hotpoHelper':
        hotpoHelper num count
                      | even num = hotpoHelper (truncate (num / 2)) (count + 1)
                      | otherwise = hotpoHelper (3 * num + 1) (count + 1)

take (truncate (5/2)) [1,2,3]的作品,所以我无法理解该错误消息。 我在哪里去了?

有帮助吗?

解决方案

Haskell中/运算符用于浮点除法。如果你真的想用浮点除法和truncate,你会在fromIntegral使用num首先将其转换为一个浮点数。你得到的错误是说,你不能用分数划分上的整数倍(5/2的作品,因为编译器推断两个数字的浮点类型)。然而,你可以做你想做的更容易,使用div功能。这通常用于缀,通过与反引号包围函数名(这适用于任何的Haskell功能):

| even num = hotpoHelper (num `div` 2) (count+1)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top