Haskell:将除法结果转换为整数类型时出现问题 [英] Haskell : Problem converting result of division to integral type

查看:186
本文介绍了Haskell:将除法结果转换为整数类型时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习Haskell并试图理解类型系统。

I'm learning Haskell and stuck trying to understand the type system.

我正在尝试编写一个函数,该函数返回 Half or输入三加一。这是我对函数的尝试,使用递归方法(该函数仅对整数输入有效):

I'm trying to write a function which returns the length of the series 'Half or Three Plus One' for an input. Here's my attempt at the function, using a recursive approach (the function is valid for integral inputs only):

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中加载此文件时

Here is the error I get when I try to load this file in 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] 有效,因此我无法理解此错误消息。
我要去哪里了?

take (truncate (5/2)) [1,2,3] works, so I'm unable to understand this error message. Where am I going wrong?

推荐答案

/ Haskell中的运算符用于浮点除法。如果您确实想使用浮点除法和截断,则可以在 fromIntegral > num 首先将其转换为浮点数。您得到的错误是您不能对整数使用分数除法(5/2可以工作,因为编译器会推断两个数字都为浮点类型)。但是,您可以使用 div 函数更轻松地完成所需的操作。通常用infix来表示,方法是用反引号将函数名引起来(这适用于任何Haskell函数):

The / operator in Haskell is used for floating point division. If you really did want to use floating point division and truncate, you'd use fromIntegral on num first to convert it to a floating point number. The error you get is saying that you can't use fractional division on an integral number (5/2 works because the compiler infers a floating point type for both numbers). However, you can do what you want much more easily, using the div function. This is typically used infix, by surrounding the function name with backquotes (this works for any Haskell function):

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

这篇关于Haskell:将除法结果转换为整数类型时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆