1

我正在学习 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]有效,因此我无法理解此错误消息。我哪里错了?

4

1 回答 1

10

Haskell 中的/运算符用于浮点除法。如果你真的想使用浮点除法 and truncate,你会先使用fromIntegralonnum将其转换为浮点数。您得到的错误是说您不能对整数使用小数除法(5/2 有效,因为编译器为这两个数字推断出浮点类型)。div但是,您可以使用该功能更轻松地做您想做的事。这通常用于中缀,通过用反引号将函数名称括起来(这适用于任何 Haskell 函数):

| even num = hotpoHelper (num `div` 2) (count+1)
于 2010-11-17T10:02:21.080 回答