I am trying to understand how to convert functions to point-free notation in Haskell. I saw this example, but it is more complicated than what I am looking for. I feel like I understand the logic behind it, but when I am trying to execute some simple examples in code I am getting compile errors. I want to try and write this function in point-free style:
f x = 5 + 8/x
which I rearranged as f x = (+) 5 $ (/) 8 x
So, I thought it might be something like this:
f = (+) 5 $ (/) 8
but when I run this in ghci I get this message:
No instance for (Num (a0 -> a0))
arising from the literal `5' at Test.hs:3:9
Possible fix: add an instance declaration for (Num (a0 -> a0))
In the first argument of `(+)', namely `5'
In the first argument of `($)', namely `(+) 5'
In the expression: (+) 5 $ (/) 8
Failed, modules loaded: none.
I don't understand the "No instance for..." message. What do I need to do to write this function in point-free style?
$
has a very low precedence. So, f x = (+) 5 $ (/) 8 x
actually means f x = (+) 5 $ ((/) 8 x)
. Instead, rewrite that as
f x = (+) 5 ( (/) 8 x)
f x = ((+) 5) ( ((/) 8) x)
f x = ((+) 5) . ( ((/) 8) ) x
f = ((+) 5) . ( (/) 8 )
f = (5+) . (8/)
The last expression makes sense: f is the composition of two operations, first divide 8 by what one has, and then add 5 to the result. Remember, g.h
means "apply h, then apply g the the result of that".