【问题标题】:Haskell : Problem converting result of division to integral typeHaskell:将除法结果转换为整数类型的问题
【发布时间】:2010-11-17 09:45:38
【问题描述】:

我正在学习 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 typeclass division collatz


    【解决方案1】:

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

    | even num = hotpoHelper (num `div` 2) (count+1)
    

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多