I get a warning to eta reduce the following lambda expression.
\(DataType arg1 arg2) -> DataType (modify arg1) arg2
The internet tells me eta-reducing means to leave out unnecessary lambdas.
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)
. 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. 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:
\a b -> f b a
Now, if we wanted to reduce this lambda we could define a higher order function
flip f a b = f b a
And write it as simply
flip f
(Note that flip
already exists in 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
\a b -> f a . g b . h
And in general, you can usually swap $
s for .
s and drop the last argument.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.