gpt4 book ai didi

haskell - 这两个函数类型定义有什么区别?

转载 作者:行者123 更新时间:2023-12-03 14:38:53 24 4
gpt4 key购买 nike

对于以下平凡的函数定义:

printLength1::(Num a)=>String->a
printLength1 s = length s


printLength2::String->Int
printLength2 s = length s

为什么它们不一样?在什么情况下我应该选择一个?

我收到了 printLength1 的这个错误:
Couldn't match type `a' with `Int'
`a' is a rigid type variable bound by
the type signature for rpnc :: String -> a at test.hs:20:1
In the return type of a call of `length'
In the expression: length s
In an equation for `rpnc': rpnc s = length s

我理解这个错误。但是我该如何解决这个问题?
我已经在这里阅读了一些关于刚性类型变量的帖子,但仍然无法理解如何修复它。

最佳答案

第一种类型签名更通用。这意味着结果可以是任何 Num --它的返回类型是多态的。所以你的第一个函数的结果可以用作 IntInteger或任何其他 Num实例。

问题是length返回 Int而不是任何 Num实例。您可以使用 fromIntegral 解决此问题:

printLength1 :: Num a => String -> a
printLength1 s = fromIntegral $ length s

注意 fromIntegral . length的签名(这是上面代码的免点版本)是 Num c => [a] -> c .这与您为 printLength1 指定的签名相匹配功能。

关于haskell - 这两个函数类型定义有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8319832/

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