Reputation: 339
What are the functions that begin with ($)
or (>>=)
supposed to do. I'm not asking exactly what $
or >>=
mean but I understand that
f :: Int -> Int
f x = x+2
is a function that takes an integer and adds two, but whilst learning Haskell I've ran into problems where the solution has been something like the following:
($) :: (a -> b) -> (a -> b)
f $ x = f x
from What does $ mean/do in Haskell?
I assume this means the function ($) takes a lambda (a -> b) and outputs a lambda (a -> b), and then the next line I'm unsure.
but I always assumed the function definition
f :: Int -> Int
had to be followed by a function with arguments starting with f like my first code example.
Thanks
Upvotes: 0
Views: 142
Reputation: 120711
Infix applications like 1 + 2
or f $ x
are just syntactic sugar for (+) 1 2
and ($) f x
, respectively. This is regardless of whether they appear in a pattern match (left side of =
) or in an expression. So, your snippets desugar to
f :: Int -> Int
f x = (+) x 2
($) :: (a -> b) -> (a -> b)
($) f x = f x
The latter could also be written
apply :: (a -> b) -> a -> b
apply f x = f x
The syntax rule is: if an identifier consists of letters (and possibly numbers, in non-leading position) it's parsed as a function with all arguments on the right, or simply as a constant value if there are no arguments. If it consists of any other symbols and is not surrounded by parentheses, it's parsed as an infix, i.e. desugared so whatever stands on the left is used as the first argument and whatever stands on the right the second argument.
Upvotes: 7