gpt4 book ai didi

haskell - 实现 curry 功能

转载 作者:行者123 更新时间:2023-12-02 06:58:58 24 4
gpt4 key购买 nike

我目前正在阅读 Graham Hutton 的“programming in haskell”,刚刚接触到 currying 和函数组合。在练习部分,有一个任务是从头开始实现 curry 函数,这已经存在于前奏模块中。

这是我的实现,但它不起作用。任何人都可以解释(我是函数式编程的新手)为什么它不起作用

my_curry :: ((a ,b) -> c) -> (a -> b -> c)
my_curry origFunc = origFunc.combine
where
combine e f = (e, f)

这里是错误[已添加]

[1 of 1] Compiling Main             ( higher_order.hs, interpreted )

higher_order.hs:92:30:
Couldn't match type `t0 -> (a, t0)' with `(a, b)'
Expected type: a -> (a, b)
Actual type: a -> t0 -> (a, t0)
In the second argument of `(.)', namely `combine'
In the expression: origFunc . combine
In an equation for `my_curry':
my_curry origFunc
= origFunc . combine
where
combine e f = (e, f)

最佳答案

问题是 . 是为了采用单个参数函数并将它们粘合在一起,

在这种情况下,combine 的类型为 a -> b -> (a, b)。所以它的第一个参数是 a 并且它的返回类型是 b -> (a, b) (记住 -> 分组在右边) .所以 . 有类型

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

由于 combine 是第二个参数,haskell 将统一 . 的类型变量,例如

(.).a ~ combine.a
(.).b ~ (combine.b -> (combine.a, combine.b))

我使用 foo.bar 表示 foo 定义中的类型变量 bar。接下来我们将其作为 (a, b) -> c 类型输入到 origFunc 中。现在,当我们尝试将其放入 . 时,我们得到了

(.).b ~ my_curry.(a, b)
(.).c ~ my_curry.c

但是等等! b 不能同时是 (a, b)b -> (a, b) ,因此类型错误。

相反,我们有两个选择,我们可以创建一种新型的组合

(..) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
f .. g = \a b -> f (g a b)

注意这如何允许 g 接受两个参数,并且您的函数变为

 my_curry origFunc = combine .. origFunc

或者我们可以只使用柯里化(Currying)

 my_curry origFunc x y = origFunc (x, y)

关于haskell - 实现 curry 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25555158/

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