Haskell:将特定类型的函数与通用类型的函数组合起来?

发布于 2024-12-23 16:56:37 字数 661 浏览 2 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悍妇囚夫 2024-12-30 16:56:37

<代码>总和。 map 不是您要查找的定义。请注意,

 (.) :: (b -> c) -> (a -> b) -> a -> c

点运算符接受两个一元函数。它不起作用,因为 map 需要两个参数:

map :: (a -> b) -> [a] -> [b]

可能的解决方案之一是显式绑定 map 的第一个参数:

myFunc :: Num c => (a -> c) -> [a] -> c
myFucc f = sum . map f

或者您可以使用 咖喱uncurry 并达到相同的结果。

myFunc = curry $ sum . uncurry map

sum . map isn't a definition you're looking for. Observe that

 (.) :: (b -> c) -> (a -> b) -> a -> c

The dot operator accepts two unary functions. It doesn't work as map takes two arguments:

map :: (a -> b) -> [a] -> [b]

One of possible solutions would be to explicitly bind map's first argument:

myFunc :: Num c => (a -> c) -> [a] -> c
myFucc f = sum . map f

Alternatively you could use curry and uncurry and achieve the same result.

myFunc = curry $ sum . uncurry map
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文