转换浮动到整数
问题描述:
我试图定义:转换浮动到整数
square :: Integer -> Integer
square = round . (** 2)
和我得到:
<interactive>:9:9: error:
• No instance for (RealFrac Integer) arising from a use of ‘round’
• In the first argument of ‘(.)’, namely ‘round’
In the expression: round . (** 2)
In an equation for ‘square’: square = round . (** 2)
<interactive>:9:18: error:
• No instance for (Floating Integer)
arising from an operator section
• In the second argument of ‘(.)’, namely ‘(** 2)’
In the expression: round . (** 2)
In an equation for ‘square’: square = round . (** 2)
我还在这个语言新,我似乎是不能转换的实例浮动到整数。有谁知道我该怎么做?
答
Haskell有多个指数函数与不同的类型:
(^) :: (Num a, Integral b) => a -> b -> a
(^^) :: (Fractional a, Integral b) => a -> b -> a
(**) :: Floating a => a -> a -> a
你正在寻找的一个就是(^)
。有了它,你甚至不需要round
:
square :: Integer -> Integer
square = (^ 2)
答
这是一个附录亚历克的回答,这是正确的,帮助你理解的错误消息。该类型的(**)
是
(**) :: (Floating a) => a -> a -> a
所以
(** 2) :: (Floating a) => a -> a
(因为字面2
可以是我们所需要的任何数字型)。但是a
是Integer
,因为你的函数声明为Integer
作为输入。所以,现在
(** 2) :: Integer -> Integer --provided that there is a `Floating Integer` instance
这说明你的第二个错误,因为没有Floating
Integer
实例 - Integer
■不要支持浮点操作,如sin
(与任意实数幂)。
然后你通过这个功能,这是一个Integer
的输出,一起round
其类型
round :: (RealFrac a, Integral b) => a -> b
我们知道输入,a
,是Integer
,因为它是从(** 2)
作为我们讨论的到来,和输出b
也是Integer
,因为您的函数的输出被声明为Integer
。所以,现在你有
round :: Integer -> Integer
--provided there are `Integral Integer` and `RealFrac Integer` instaces
有一个Integral
Integer
实例,以便使用,但没有RealFrac
Integer
实例,并解释你的第一个错误。 Integer
s不支持像提取分子一样的类似理性的操作(尽管我想他们可以......)。
答
的附录中@ luqui的答案,如果你想修正这个错误(而不是仅仅关注@亚历克的优秀的解决方案),你可以在Integer
参数转换到一个Floating
实例:
square :: Integer -> Integer
square = round . (** 2) . fromInteger
这是卢基的答案是否可以用于评论亚历克的答案,这是值得商榷的,但这肯定可能是对卢奎答案的评论。 – chepner