gpt4 book ai didi

Haskell 签名 : basics

转载 作者:行者123 更新时间:2023-12-03 14:39:56 28 4
gpt4 key购买 nike

为什么这不完全有效?

sum :: (Num a, Num b) => a -> b -> c
sum a b = a + b

当然,错误消息与签名有关,但我仍然不明白原因。
Couldn't match expected type ‘a’ with actual type ‘b’
‘b’ is a rigid type variable bound by
the type signature for:
sum :: forall a b c. (Num a, Num b) => a -> b -> c

‘a’ is a rigid type variable bound by
the type signature for:
sum :: forall a b c. (Num a, Num b) => a -> b -> c

In the second argument of ‘(+)’, namely ‘b’
In the expression: a + b
In an equation for ‘sum’: sum a b = a + b

我错过了什么?

最佳答案

因为(+)函数有签名:

(+) :: Num a => a -> a -> a

这意味着 (+)功能 要求操作数具有相同的类型 ,并且结果与操作数具有相同的类型。

您的签名意味着程序员可以选择任何 Num键入作为第一个操作数,以及任何 Num type 作为第二个操作数,然后构造任何类型。所以这意味着我可以将函数专门化为 sum :: Int -> Float -> Char ,但没有这样的 (+)定义。

我们可以使类型更灵活,例如使用 fromIntegral :: (Integral a, Num b) => a -> b :
integralSum :: (Integral i, Integral j, Num c) => i -> j -> c
integralSum x y = fromIntegral x + fromIntegral y

关于Haskell 签名 : basics,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599388/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com