2016-11-28 77 views
2

我试图定义:转换浮动到整数

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) 

我还在这个语言新,我似乎是不能转换的实例浮动到整数。有谁知道我该怎么做?

回答

5

这是一个附录亚历克的回答,这是正确的,帮助你理解的错误消息。该类型的(**)

(**) :: (Floating a) => a -> a -> a 

所以

(** 2) :: (Floating a) => a -> a 

(因为字面2可以是我们所需要的任何数字型)。但是aInteger,因为你的函数声明为Integer作为输入。所以,现在

(** 2) :: Integer -> Integer --provided that there is a `Floating Integer` instance 

这说明你的第二个错误,因为没有FloatingInteger实例 - 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 

有一个IntegralInteger实例,以便使用,但没有RealFracInteger实例,并解释你的第一个错误。 Integer s不支持像提取分子一样的类似理性的操作(尽管我想他们可以......)。

1

的附录中@ luqui的答案,如果你想修正这个错误(而不是仅仅关注@亚历克的优秀的解决方案),你可以在Integer参数转换到一个Floating实例:

square :: Integer -> Integer 
square = round . (** 2) . fromInteger 
+0

这是卢基的答案是否可以用于评论亚历克的答案,这是值得商榷的,但这肯定可能是对卢奎答案的评论。 – chepner