Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify anonymous function in higer order functions

Assuming I have the following types:

data Test = Test1 | Test2
            deriving (Eq, Show)

data TestDS = TestDS {
      testField1 :: String,
      testField2 :: Test
    } deriving (Eq, Show)

testFilter :: [TestDS] -> [TestDS]
testFilter tdata = filter (\x -> testField2 x == Test2) tdata

Is it possible to convert the above filter function to the following form:

filter (Test2 == testField2) tdata

(The above filter function of course produces a compile error)

like image 515
Sibi Avatar asked Apr 10 '26 13:04

Sibi


2 Answers

Is this what you want?

filter ((Test2 ==) . testField2) tdata

Remember that (Test2 ==) and testField2 are both functions that can be composed.

like image 86
jamshidh Avatar answered Apr 13 '26 02:04

jamshidh


filter (\x -> testField2 x == Test2) tdata

It seems you put parentheses incorrectly in your mind. The code is not

filter ((\x -> testField2 x) == Test2) tdata

It is really

filter (\x -> (testField2 x == Test2)) tdata

So eta-reduction rule ("\x -> foo x can be replaced with foo") is not applicable.

To have it applicable you need to move x to the end of lambda body. Firstly we use commutativity of ==:

filter (\x -> (Test2  == (testField2 x))) tdata

I put extra parentheses to clarify that eta-reduction is still not applicable. Now the idea is to apply function composition rule ("foo (bar x) can be replaced with foo . bar"), but to demonstrate what are foo and bar in our example I will use prefix form of ==:

filter (\x -> ((==) Test2 (testField2 x))) tdata

Now it's clear that foo is (==) Test2 and bar is textField2:

filter ((==) Test2 . testField2)) tdata

Now instead of (==) Test2 we can use so called operator section. (== foo) (parentheses are mandatory) is the same as \x -> x == foo. (foo ==) is the same as 'x -> foo == x.

filter ((== Test2) . testField2)) tdata

or

filter ((Test2 ==) . testField2)) tdata
like image 38
nponeccop Avatar answered Apr 13 '26 02:04

nponeccop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!