Haskell:将特定类型的函数与通用类型的函数组合起来?
我正在 GHCi 中写一篇简短的单行文章,并尝试用地图来求和。我认为它失败的原因是因为 map 给出了一般类型 [b] 的输出,而 sum 接受特定输入 Num a => [一个]。然而,假设map函数的输出类型为Num b =>,这段代码没有任何问题。 [b].
我认为编写限制类型声明可能会起作用(尽管我猜这会阻止您在 GHCi 中执行此操作),但它仍然不起作用:
myFunc :: Num b => (a -> b) -> [a] -> b
myFunc = sum . map
给了我以下错误:
Couldn't match expected type `[[a] -> b]'
with actual type `[a] -> [b]'
Expected type: (a -> b) -> [[a] -> b]
Actual type: (a -> b) -> [a] -> [b]
In the second argument of `(.)', namely `map'
In the expression: sum . map
有什么方法可以做到这一点吗?也许我只是错过了一些明显的东西(对于 Haskell 来说是新的)。
I was writing a quick one-liner in GHCi and tried to compose sum with map. I figured the reason it failed is because map gives output of a general type [b] whereas sum takes in specific input Num a => [a]. However, there is nothing wrong with this code assuming that the output of the map function is type Num b => [b].
I thought writing a restricting type declaration might work (although I guess that prevents you from doing it in GHCi) but it still didn't:
myFunc :: Num b => (a -> b) -> [a] -> b
myFunc = sum . map
Gave me the following error:
Couldn't match expected type `[[a] -> b]'
with actual type `[a] -> [b]'
Expected type: (a -> b) -> [[a] -> b]
Actual type: (a -> b) -> [a] -> [b]
In the second argument of `(.)', namely `map'
In the expression: sum . map
Is there any way to do this? Maybe I am just missing something obvious (new to Haskell).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
<代码>总和。 map 不是您要查找的定义。请注意,
点运算符接受两个一元函数。它不起作用,因为
map
需要两个参数:可能的解决方案之一是显式绑定
map
的第一个参数:或者您可以使用
咖喱
和uncurry
并达到相同的结果。sum . map
isn't a definition you're looking for. Observe thatThe dot operator accepts two unary functions. It doesn't work as
map
takes two arguments:One of possible solutions would be to explicitly bind
map
's first argument:Alternatively you could use
curry
anduncurry
and achieve the same result.