简体   繁体   English

减少数据修改的Eta

[英]Eta reduction for data modification

I get a warning to eta reduce the following lambda expression. 我收到一个警告,要求减少以下lambda表达式。

\(DataType arg1 arg2) -> DataType (modify arg1) arg2

The internet tells me eta-reducing means to leave out unnecessary lambdas. 互联网告诉我eta-reducing意味着省去不必要的lambda。

map (\x -> fun x) list
map fun list

How is that applicable to the code above? 这怎么适用于上面的代码? Am I perhaps just missing a basic syntax for modifying data types? 我可能只是缺少修改数据类型的基本语法?

For this case you can't eta reduce it any further. 对于这种情况,你不能再进一步减少它。 There is only a single argument to the lambda, namely (DataType arg1 arg2) . lambda只有一个参数,即(DataType arg1 arg2) These are not separate arguments, as indicated by the parentheses, but instead you are pattern matching on a constructor. 这些不是单独的参数,如括号所示,而是在构造函数上进行模式匹配。 In reality, the compiler will reduce this expression to something more like 实际上,编译器会将此表达式减少为更类似的表达式

\arg -> case arg of
    DataType arg1 arg2 -> DataType (modify arg1) arg2

Here it is more clear that there is only one argument to the lambda, and it is not used in such a way that it can be reduced. 这里更清楚的是,lambda只有一个参数,并且它没有以可以减少它的方式使用。 The main rule for reduction is when you have something like 减少的主要规则是你有类似的东西

\a b c -> f b a c

The c argument appears as the last term in the argument declaration and in the expression, so it can be dropped: c参数显示为参数声明和表达式中的最后一个术语,因此可以删除它:

\a b -> f b a

Now, if we wanted to reduce this lambda we could define a higher order function 现在,如果我们想减少这个lambda,我们可以定义一个更高阶的函数

flip f a b = f b a

And write it as simply 并简单地写出来

flip f

(Note that flip already exists in Prelude ). (需要注意的是flip已经存在Prelude )。

Another rule you can apply is when dealing with the $ operator. 您可以应用的另一个规则是处理$运算符时。 Put simply, if you have something like 简而言之,如果你有类似的东西

\a b c -> f a $ g b $ h c

Then you can first turn this into a composition: 然后你可以先把它变成一个组合:

\a b c -> (f a . g b . h) c

And now it is simple to drop the c argument 现在删除c参数很简单

\a b -> f a . g b . h

And in general, you can usually swap $ s for . 一般来说,你通常可以交换$ s . s and drop the last argument. s并删除最后一个参数。

Again, this doesn't apply in your case because your function only has 1 argument, and that argument is pattern matched on to pull out a constructor's arguments, then an entirely new value is reconstructed from it. 同样,这不适用于您的情况,因为您的函数只有1个参数,并且该参数是模式匹配的,以提取构造函数的参数,然后从中重构一个全新的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM