本文介绍了为什么我无法在Haskell中将Integer添加到Double中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以这样做:

1 + 2.0

但是当我尝试时:

but when I try:

let a = 1
let b = 2.0
a + b

<interactive>:1:5:
    Couldn't match expected type `Integer' with actual type `Double'
    In the second argument of `(+)', namely `b'
    In the expression: a + b
    In an equation for `it': it = a + b

这看起来很奇怪!它是否曾经让你失望?

This seems just plain weird! Does it ever trip you up?

P.S .:我知道1和2.0是多态常量。这不是我担心的事情。让我担心的是,为什么哈斯克尔在第一种情况下做了一件事情,而在另一件事情中又做了另一件事情!

P.S.: I know that "1" and "2.0" are polymorphic constants. That is not what worries me. What worries me is why haskell does one thing in the first case, but another in the second!

推荐答案

您可以使用GHCI了解更多关于此的信息。使用命令:t 来获取表达式的类型。

You can use GHCI to learn a little more about this. Use the command :t to get the type of an expression.

Prelude> :t 1
1 :: Num a => a

所以 1 是一个常数,可以是任何数字类型( Double , Integer 等)。

So 1 is a constant which can be any numeric type (Double, Integer, etc.)

Prelude> let a = 1
Prelude> :t a
a :: Integer

所以在这种情况下,Haskell推断了 a 是整数。同样,如果你写 let b = 2.0 ,Haskell推断类型 Double 。使用 let 使得Haskell推断出比(可能)更为具体的类型,并且这会导致您的问题。 (比我更有经验的人也许可以评论为什么会出现这种情况。)由于(+)的类型为 Num a => a - > a - >一个,这两个参数需要具有相同的类型。

So in this case, Haskell inferred the concrete type for a is Integer. Similarly, if you write let b = 2.0 then Haskell infers the type Double. Using let made Haskell infer a more specific type than (perhaps) was necessary, and that leads to your problem. (Someone with more experience than me can perhaps comment as to why this is the case.) Since (+) has type Num a => a -> a -> a, the two arguments need to have the same type.

您可以使用 fromInteral function:

You can fix this with the fromIntegral function:

Prelude> :t fromIntegral
fromIntegral :: (Num b, Integral a) => a -> b

该函数将整数类型转换为其他数字类型。例如:

This function converts integer types to other numeric types. For example:

Prelude> let a = 1
Prelude> let b = 2.0
Prelude> (fromIntegral a) + b
3.0

这篇关于为什么我无法在Haskell中将Integer添加到Double中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 04:32