How to get rid of parentheses when passing operator functions

Beginner’s question: Say, from a list of numbers I want to remove all 17s – and I don’t want to use the elem function, only filter and operators.

My first approach was:

filter (\x -> x /= 17) lst

That works, but can be condensed to:

filter ((/=) 17) lst

When I see Haskell code (say on GitHub) it rarely has multiple parentheses – thus I assume the way I wrote this filter expression is not very “haskellonic” (like “pythonic”).

So here comes my question: Is there a way to write this expression with no or only one pair of parentheses?

PS: I tried the apply operator $:

filter $ (/=) 17 lst

but this doesn’t work. (I guess the compiler can’t resolve this syntactically).

1 Like

Actually the Haskell language server helped me out! I can just write:

filter (/= 17) lst

So the parentheses (/=) are not needed if there are parentheses around the whole function expression!

1 Like

You have stumbled upon operator sections (Haskell 98 Report, section 3.5). They are very useful when writing concise one-liners.


Following HLS’s tips will help you learn the parenthesesless patterns, which is great, and I’m glad it helped you figure this one out.

Here are a couple of notes:

Writing (\x -> x /= 17) is morally equivalent to ((/=) 17) only because you can switch the order of the arguments for /=. If seen literally, it’s a different function because the arguments are flipped: ((/=) 17) = (\x -> (/=) 17 x) = (\x -> 17 /= x)

The $ operator is simply function application but it has the lowest binding precedence:

f $ x = f x

To make it easier at first, I used to imagine a big axe that splits the line in two, and then apply the left side to the right side:

Use the big axe to split the line where the operator is:

filter ||||||||||||||||||| (/=) 17 lst

Then apply the left side of the split to the right one:

right = (/=) 17 lst -- can you tell me the type of this? hint: it explains why it didn't work
left  = filter

and then you apply the left side to the right hand side:

left right
-- which is
filter (17 /= lst)

Happy learning :slight_smile:


Thank you very much for the detailed thus patient explanations @romes !

1 Like