无法定义采用 Int 和 Float 的函数
Can't define a function taking an Int and a Float
a.hs
文件有:
a :: Float -> Int -> Int
a b c = b + c
在ghci中加载,错误为:
Couldn't match expected type ‘Int’ with actual type ‘Float’
和
Couldn't match expected type ‘Float’ with actual type ‘Int’
如果参数和结果都是 int 或 float,则有效。
这是为什么?谢谢!
(+)
的类型签名是:
(+) :: Num a => a -> a -> a
这意味着两个参数(您的 b
和 c
)必须属于同一类型。
正如 Ismor 评论的那样,您可以使用 fromIntegral
:
fromIntegral :: (Integral a, Num b) => a -> b
将 c
从 Int
转换为 Float
并让您的函数进行类型检查。
a.hs
文件有:
a :: Float -> Int -> Int
a b c = b + c
在ghci中加载,错误为:
Couldn't match expected type ‘Int’ with actual type ‘Float’
和
Couldn't match expected type ‘Float’ with actual type ‘Int’
如果参数和结果都是 int 或 float,则有效。
这是为什么?谢谢!
(+)
的类型签名是:
(+) :: Num a => a -> a -> a
这意味着两个参数(您的 b
和 c
)必须属于同一类型。
正如 Ismor 评论的那样,您可以使用 fromIntegral
:
fromIntegral :: (Integral a, Num b) => a -> b
将 c
从 Int
转换为 Float
并让您的函数进行类型检查。