gpt4 book ai didi

haskell - 为什么这个函数不能进一步减少 eta?

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

我有一个简单的功能:

calculate :: Int -> Int -> Int
calculate x y = sum . filter even $ enumFromTo x y

可以简化为

calculate x = sum . filter even . enumFromTo x

但不能进一步简化为

calculate = sum . filter even . enumFromTo

这是为什么?

我期望它能够编译,但我却收到以下错误:

    • Couldn't match type: Int -> [Int]
with: [Int -> Int]
Expected: Int -> [Int -> Int]
Actual: Int -> Int -> [Int]
• Probable cause: ‘enumFromTo’ is applied to too few arguments
In the second argument of ‘(.)’, namely ‘enumFromTo’
In the second argument of ‘(.)’, namely ‘filter even . enumFromTo’
In the expression: sum . filter even . enumFromTo
|
10 | calculate'' = sum . filter even . enumFromTo
| ^^^^^^^^^^

最佳答案

核心问题是:

calculate x = (sum . filter even . enumFromTo) x -- could be eta-reduced
calculate x = sum . filter even . (enumFromTo x) -- cannot be eta-reduced

如果您想消除 x ,您必须首先将其置于一个位置,使其成为最外层函数的唯一参数。 (在本例中,最外层函数是 (.) ,而不是 enumFromTo 。)例如,让我们写 s g 。对于 sum . gf g对于 filter even . g 。然后:

sum . filter even . enumFromTo x
=
s (filter even . enumFromTo x)
=
s (f (enumFromTo x))
=
s ((f . enumFromTo) x)
=
(s . f . enumFromTo) x
=
((sum .) . (filter even .) . enumFromTo) x

这是函数对唯一参数 x 的应用。 ,所以现在我们可以进行 eta-reduce。

calculate = (sum .) . (filter even .) . enumFromTo

关于haskell - 为什么这个函数不能进一步减少 eta?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75514600/

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