I started learning Haskell and I encountered a problem I can't just understand. I've got a method used to find value from a list of key-value list (from this page):
let findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs
I tried fiddling with a bit and decided to get rid of $ sign in this way:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) ( xs )
However, it doesn't even parse (filter applied to too many argumens error). I've read that $ sign is used to simply replace parenthesis and I can't figure out why this simple change of code is bad. Could someone explain it to me?
The infix operator ($) is just "function application". In other words
f x -- and
f $ x
are the same. Since in Haskell parentheses are only used to disambiguate precedence (and for tuple notation and a few other minor places, see comments) we can also write the above in a few other ways
f x
f $ x
(f) x
f (x)
(f) (x) -- and even
(f) $ (x)
In every case, the above expressions denote the same thing: "apply the function f to the argument x".
So why have all this syntax? ($) is useful for two reasons
It has really low precedence so it can stand in for a lot of parentheses sometimes
It's nice to have an explicit name for the action of function application
In the first case, consider the following deeply right-nested function application
f (g (h (i (j x))))
It can be a little difficult to read this and a little difficult to know you have the right number of parentheses. However, it's "just" a bunch of applications so there ought to be a representation of this phrase using ($). Indeed there is
f $ g $ h $ i $ j $ x
Some people find this easier to read. More modern style also incorporates (.) in order to emphasize that the whole left side of this phrase is just a composed pipeline of functions
f . g . h . i . j $ x
And this phrase is, as we saw above, identical to
(f . g . h . i . j) x
which is sometimes nicer to read.
There are also times when we want to be able to pass around the idea of function application. For instance, if we have a list of functions
lof :: [Int -> Int]
lof = [ (+1), (subtract 1), (*2) ]
we might want to map application by a value over them, for instance apply the number 4 to each function
> map (\fun -> fun 4) lof
[ 5, 3, 8 ]
But since this is just function application, we can also use section syntax over ($) to be a bit more explicit
> map ($ 4) lof
[ 5, 3, 8 ]
The operator $ has the lowest priority, so
snd . head . filter (\(k,v) -> key == k) $ xs
is read as
(snd . head . filter (\(k,v) -> key == k)) xs
while your second expression is rather
snd . head . ( filter (\(k,v) -> key == k) xs )
The $ sign isn't magic syntax for replacing parentheses. It's an ordinary infix operator, in every way that an operator like + is.
Putting brackets around a single name like ( xs ) is always equivalent to just xs1. So if that's what the $ did, then you'd get the same error either way.
Try to imagine what would happen if you had some other operator you're familiar with there, such as +:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) + xs
Ignore the fact that + works on numbers so this makes no sense, and just think about the structure of the expression; which terms are being recognised as functions, and which terms are being passed to them as arguments.
In fact, using + there does actually parse and typecheck successfully! (It gives you a function with nonsense type class constraints, but if you fulfill them it does mean something). Lets walk through how the infix operators are resolved:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) + xs
The highest precedence thing is always normal function application (just writing terms next to each other, with no infix operators involved). There's only one example of that here, filter applied to the lambda definition. That gets "resolved", and becomes a single sub-expression as far as parsing the rest of the operators is concerned:
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
in snd . head . fileterExp + xs
The next highest precedence thing is the . operator. We've got several to choose from here, all with the same precedence. The . is right associative, so we take the rightmost one first (but it wouldn't actually change the result whichever one we pick, because the meaning of the . is an associative operation, but the parser has no way of knowing that):
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
dotExp1 = head . filterExp
in snd . dotExp1 + xs
Note that the . grabbed the terms immediately to its left and right. This is why precedence is so important. There's still a . left, which is still higher precedence than +, so it goes next:
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
dotExp1 = head . filterExp
dotExp2 = snd . dotExp1
in dotExp2 + xs
And we're done! + has lowest precedence of the operators here, so it gets its arguments last, and ends up being the top-most call in the whole expression. Note that the + being low precedence prevented the xs being "claimed" as an argument by any of the higher precedence applications to the left. And if any of them had been lower precedence, they would have ended up taking the whole expression dotExp2 + xs as an argument, so they still couldn't have got to xs; putting an infix operator before xs (any infix operator) prevents it from being claimed as an argument by anything to the left.
This is in fact exactly the same way that $ is parsed in this expression, because . and $ happen to have the same relative precedence that . and + have; $ is designed to have extremely low precedence, so it will work this way with almost any other operators involved to the left and right.
If we don't put an infix operator between the filter call and xs, then this is what happens:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) xs
Normal function application goes first. Here we've got 3 terms simply next to each other: filter, (\(k,v) -> key == k), and xs. Function application is left associative, so we take the leftmost pair first:
let findKey key xs
= let filterExp1 = filter (\(k,v) -> key == k)
in snd . head . filterExp1 xs
There's still another normal application left, which is still higher precedence than the ., so we do that:
let findKey key xs
= let filterExp1 = filter (\(k,v) -> key == k)
filterExp2 = filterExp1 xs
in snd . head . filterExp2
Now the first dot:
let findKey key xs
= let filterExp1 = filter (\(k,v) -> key == k)
filterExp2 = filterExp1 xs
dotExp = head . filterExp2
in snd . dotExp
And we're done, the top-most call in the whole expression this time was the left-most . operator. This time xs got sucked in as a second argument to filter; this is sort-of where we want it since filter does take two arguments, but it leaves the result of filter in a function composition chain, and filter applied to two arguments can't return a function. What we wanted was to apply it to one argument to give a function, have that function be part of the function composition chain, and then apply that entire function to xs.
With $ there, the final form mirrors that when we used +:
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
dotExp1 = head . filterExp
dotExp2 = snd . dotExp1
in dotExp2 $ xs
It's parsed exactly the same way as when we had +, so the only difference is that where + means "add my left argument to my right argument", $ means "apply my left argument as a function to my right argument". Which is what we wanted to happen! Huzzah!
TLDR: The bad news is that $ doesn't work by just wrapping parentheses; it's more complicated than that. The good news is that if you understand how Haskell resolves expressions involving infix operators, then you understand how $ works. There is nothing at all special about it as far as the language is concerned; it's an ordinary operator you could define yourself if it didn't exist.
1 Parenthesising an operator like (+) also just gives you exactly the same function denoted by +, but now it doesn't have the special infix syntax, so this does affect how things are parsed in this case. Not so with ( xs ) where it's just a name inside.
"$ sign is used to simply replace parenthesis" is pretty much correct – however, it effectively parenthesises everything to both sides! So
snd . head . filter (\(k,v) -> key == k) $ xs
is effectively
( snd . head . filter (\(k,v) -> key == k) ) ( xs )
Of course, the parens around xs are unneeded here (that's an "atom" anyway), so the relevant ones are in this case around the left side. Indeed that happens often in Haskell, because the general philosophy is to think about functions as abstract entities as much as possible, rather than the particular values involved when applying the function to some argument. Your definition could also be written
let findKey key xs' = let filter (\(k,v) -> key == k) $ xs
x0 = head xs'
v0 = snd x0
in v0
That would be extremely explicit, but all those intermediate values aren't really interesting. So we prefer to simply chain the functions together "point-free", with .. That often gets us rid of a lot of boilerplate, indeed for your definition the following can be done:
η-reduction of the xs. That argument just passed on to the chain of functions, so we might as well say "findKey key" is that chain, with whatever argument you supply"!
findKey key = snd . head . filter (\(k,v) -> key == k)
Next, we can avoid this explicit lambda: \(k,v) -> k is simply the fst function. You then need to postcompose comparison with key.
findKey key = snd . head . filter ((key==) . fst)
I'd stop here, since too much point-free is pointless and unreadable. But you could go on: there's new parens now around the argument to key, we can again get rid of those with $. But careful:
"findKey key = snd . head . filter $ (key==) . fst"
is not right, because the $ would again parenthesise both sides, yet (snd . head . filter) is not well-typed. Actually snd . head should only come after both arguments to filter. A possible way to do such a post-post-composition is using the function functor:
findKey key = fmap (snd . head) . filter $ (key==) . fst
...we could go on even further and get rid also of the key variable, but it wouldn't look nice. I think you've got the point...
Other answers have commented in detail on how ($) can replace parentheses, since ($) was defined as an application operator with the right precedence.
I'd like to add that GHC, in order to make it possible to replace parentheses with ($), uses some more magic under the hood than what can be seen from the definition of ($). When higher rank functions are involved, the type system can cope with higher-rank arguments when passed through standard application (as in f x), but not when passed though an application operator (as in f $ x). To overcome this problem, GHC handles ($) in a special way in the type system. Indeed, the following code shows that if we define and use our own application operator ($$), the type system does not apply the same magic handling.
{-# LANGUAGE RankNTypes #-}
-- A higher rank function
higherRank :: (forall a. a -> a -> a) -> (Int, Char)
higherRank f = (f 3 4, f 'a' 'b')
-- Standard application
test0 :: (Int, Char)
test0 = higherRank const -- evaluates to (3,'a')
-- Application via the ($) operator
test1 :: (Int, Char)
test1 = higherRank $ const -- again (3, 'a')
-- A redefinition of ($)
infixr 0 $$
($$) :: (a -> b) -> a -> b
($$) = ($)
test2 :: (Int, Char)
test2 = higherRank $$ const -- Type error (!)
-- Couldn't match expected type `forall a. a -> a -> a'
-- with actual type `a0 -> b0 -> a0'
Related
What is the difference between the dot (.) and the dollar sign ($)?
As I understand it, they are both syntactic sugar for not needing to use parentheses.
The $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.
For example, let's say you've got a line that reads:
putStrLn (show (1 + 1))
If you want to get rid of those parentheses, any of the following lines would also do the same thing:
putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1
The primary purpose of the . operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.
Going back to the same example:
putStrLn (show (1 + 1))
(1 + 1) doesn't have an input, and therefore cannot be used with the . operator.
show can take an Int and return a String.
putStrLn can take a String and return an IO ().
You can chain show to putStrLn like this:
(putStrLn . show) (1 + 1)
If that's too many parentheses for your liking, get rid of them with the $ operator:
putStrLn . show $ 1 + 1
They have different types and different definitions:
infixr 9 .
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(f . g) x = f (g x)
infixr 0 $
($) :: (a -> b) -> a -> b
f $ x = f x
($) is intended to replace normal function application but at a different precedence to help avoid parentheses. (.) is for composing two functions together to make a new function.
In some cases they are interchangeable, but this is not true in general. The typical example where they are is:
f $ g $ h $ x
==>
f . g . h $ x
In other words in a chain of $s, all but the final one can be replaced by .
Also note that ($) is the identity function specialised to function types. The identity function looks like this:
id :: a -> a
id x = x
While ($) looks like this:
($) :: (a -> b) -> (a -> b)
($) = id
Note that I've intentionally added extra parentheses in the type signature.
Uses of ($) can usually be eliminated by adding parenthesis (unless the operator is used in a section). E.g.: f $ g x becomes f (g x).
Uses of (.) are often slightly harder to replace; they usually need a lambda or the introduction of an explicit function parameter. For example:
f = g . h
becomes
f x = (g . h) x
becomes
f x = g (h x)
($) allows functions to be chained together without adding parentheses to control evaluation order:
Prelude> head (tail "asdf")
's'
Prelude> head $ tail "asdf"
's'
The compose operator (.) creates a new function without specifying the arguments:
Prelude> let second x = head $ tail x
Prelude> second "asdf"
's'
Prelude> let second = head . tail
Prelude> second "asdf"
's'
The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:
Prelude> let third x = head $ tail $ tail x
Prelude> map third ["asdf", "qwer", "1234"]
"de3"
If we only use third once, we can avoid naming it by using a lambda:
Prelude> map (\x -> head $ tail $ tail x) ["asdf", "qwer", "1234"]
"de3"
Finally, composition lets us avoid the lambda:
Prelude> map (head . tail . tail) ["asdf", "qwer", "1234"]
"de3"
The short and sweet version:
($) calls the function which is its left-hand argument on the value which is its right-hand argument.
(.) composes the function which is its left-hand argument on the function which is its right-hand argument.
One application that is useful and took me some time to figure out from the very short description at Learn You a Haskell: Since
f $ x = f x
and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4 +) analogous to (++ ", world") "hello".
Why would anyone do this? For lists of functions, for example. Both:
map (++ ", world") ["hello", "goodbye"]
map ($ 3) [(4 +), (3 *)]
are shorter than
map (\x -> x ++ ", world") ["hello", "goodbye"]
map (\f -> f 3) [(4 +), (3 *)]
Obviously, the latter variants would be more readable for most people.
Haskell: difference between . (dot) and $ (dollar sign)
What is the difference between the dot (.) and the dollar sign ($)?. As I understand it, they are both syntactic sugar for not needing to use parentheses.
They are not syntactic sugar for not needing to use parentheses - they are functions, - infixed, thus we may call them operators.
Compose, (.), and when to use it.
(.) is the compose function. So
result = (f . g) x
is the same as building a function that passes the result of its argument passed to g on to f.
h = \x -> f (g x)
result = h x
Use (.) when you don't have the arguments available to pass to the functions you wish to compose.
Right associative apply, ($), and when to use it
($) is a right-associative apply function with low binding precedence. So it merely calculates the things to the right of it first. Thus,
result = f $ g x
is the same as this, procedurally (which matters since Haskell is evaluated lazily, it will begin to evaluate f first):
h = f
g_x = g x
result = h g_x
or more concisely:
result = f (g x)
Use ($) when you have all the variables to evaluate before you apply the preceding function to the result.
We can see this by reading the source for each function.
Read the Source
Here's the source for (.):
-- | Function composition.
{-# INLINE (.) #-}
-- Make sure it has TWO args only on the left, so that it inlines
-- when applied to two functions, even if there is no final argument
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)
And here's the source for ($):
-- | Application operator. This operator is redundant, since ordinary
-- application #(f x)# means the same as #(f '$' x)#. However, '$' has
-- low, right-associative binding precedence, so it sometimes allows
-- parentheses to be omitted; for example:
--
-- > f $ g $ h x = f (g (h x))
--
-- It is also useful in higher-order situations, such as #'map' ('$' 0) xs#,
-- or #'Data.List.zipWith' ('$') fs xs#.
{-# INLINE ($) #-}
($) :: (a -> b) -> a -> b
f $ x = f x
Conclusion
Use composition when you do not need to immediately evaluate the function. Maybe you want to pass the function that results from composition to another function.
Use application when you are supplying all arguments for full evaluation.
So for our example, it would be semantically preferable to do
f $ g x
when we have x (or rather, g's arguments), and do:
f . g
when we don't.
... or you could avoid the . and $ constructions by using pipelining:
third xs = xs |> tail |> tail |> head
That's after you've added in the helper function:
(|>) x y = y x
My rule is simple (I'm beginner too):
do not use . if you want to pass the parameter (call the function), and
do not use $ if there is no parameter yet (compose a function)
That is
show $ head [1, 2]
but never:
show . head [1, 2]
A great way to learn more about anything (any function) is to remember that everything is a function! That general mantra helps, but in specific cases like operators, it helps to remember this little trick:
:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
and
:t ($)
($) :: (a -> b) -> a -> b
Just remember to use :t liberally, and wrap your operators in ()!
All the other answers are pretty good. But there’s an important usability detail about how ghc treats $, that the ghc type checker allows for instatiarion with higher rank/ quantified types. If you look at the type of $ id for example you’ll find it’s gonna take a function whose argument is itself a polymorphic function. Little things like that aren’t given the same flexibility with an equivalent upset operator. (This actually makes me wonder if $! deserves the same treatment or not )
The most important part about $ is that it has the lowest operator precedence.
If you type info you'll see this:
λ> :info ($)
($) :: (a -> b) -> a -> b
-- Defined in ‘GHC.Base’
infixr 0 $
This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.
So then we use it where normal function application or using () doesn't work.
So, for example, this works:
λ> head . sort $ "example"
λ> e
but this does not:
λ> head . sort "example"
because . has lower precedence than sort and the type of (sort "example") is [Char]
λ> :type (sort "example")
(sort "example") :: [Char]
But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .
I think a short example of where you would use . and not $ would help clarify things.
double x = x * 2
triple x = x * 3
times6 = double . triple
:i times6
times6 :: Num c => c -> c
Note that times6 is a function that is created from function composition.
I have a simple function, and the desire to make sense of point-free style.
shout :: String -> String
shout input
| null input = []
| otherwise = (toUpper . head $ input) : (shout . tail $ input)
My intuition led me to this
pfShout :: String -> String
pfShout = (toUpper . head) : (shout . tail)
which is complaining about the following for the first argument of the cons cell
Couldn't match expected type 'String -> String'
with actual type '[[Char] -> Char]'
Possible cause: '(:)' is applied to too many arguments
In the expression: (toUpper . head) : (pfShout . tail)
In an equation for 'pfShout':
pfShout = (toUpper . head) : (pfShout . tail)
and complaining about this for the second argument of the cons cell
Couldn't match expected type '[[Char] -> Char]'
with actual type '[Char] -> String'
Probable cause: '(.)' is applied to too few arguments
In the second argument of '(:)', namely '(pfShout . tail)'
In the expression: (toUpper . head) : (pfShout . tail)
In an equation for 'pfShout':
pfShout = (toUpper . head) : (pfShout . tail)
It's clear to me that I can't make a list out of 'String -> String' functions and '[[Char]->Char]', and I'm starting to get a to a place where I'm thinking this just isn't gonna work point-free.
I understand there are other considerations here (like now I'm missing a base-case), but . I also understand I could completely re-write the function to achieve the same effect (like map toUpper). I'm primarily interested in point-free using recursion with the function as it is written.
If it is (or isn't) possible to write this function point-free, what am I missing?
As #n.m noted you can use shout = map toUpper. However it is possible to do this without map or any other fancy functions like foldr, but we need more combinators. We need something that takes our input argument and passes it to two functions toUpper . head and shout . tail and then combines them with :. You propably don't know this function yet, but the <*> operator from applicative has what we need:
(f <*> g) x = f x (g x)
Now we can do something like this:
combine . f <*> g = \x -> combine (f x) (g x) -- [1]
I will let you figure out how exactly to apply this to your problem. ;)
But we still need to express the empty list case somehow. There are multiple ways to do this but the easiest would be the bool from Data.Bool function which is like an if function, together with join from Control.Monad.
-- [2]
bool x _ False = x
bool _ x True = x
join f x = f x x
Now we can do the following:
shout = join $ bool (not null case) (null case) . null
-- Which translates to
shout xs = bool ((not null case) xs) ((null case) xs) (null xs)
Again implementing the two cases is left as an excercise to the reader.
[1]: Instead of (.) you could also use (<$>) which for functions is the same as (.) but (<$>) and (<*>) kind of belong together. You will understand why once you learn about applicatives.
[2]: If you wonder what the reasoning behind the order of the arguments of bool is, the first argument is the False case because Bool is defined like this:
data Bool = False | True
And this order is motivated by the convention that False < True. maybe and either are two other functions that share this exact pattern with bool.
To rewrite anything in a pointfree style, install pointfree or use any one of the online versions (http://pointfree.io or https://blunt.herokuapp.com).
Your expression
\input -> (toUpper . head $ input) : (shout . tail $ input)
translates to
ap ((:) . toUpper . head) (shout . tail)
(You can substitute <*> for ap, they are interchangeable in this case).
But this is not enough. You also need to somehow end the recursion. To do that in the pointfree style you need a pointfree if or a pointfree pattern match which do not seem to exist in Haskell. In theory if could be defined as a built-in function, which would make a pointfree definition possible, but in Haskell it isn't. (One can define such a function, but its implementation would not be pointfree. So you can trade map for Data.Bool.bool, but is there a point?
Combinators like . and $ and even ap are probably not internally pointfree either, but using them doesn't feel like cheating. They only deal with functions, and thus feel somehow more fundamental than bool or map.
The point-free way to do recursion is to use Data.Function.fix, which is explained here: https://en.wikibooks.org/wiki/Haskell/Fix_and_recursion
I started learning Haskell and I encountered a problem I can't just understand. I've got a method used to find value from a list of key-value list (from this page):
let findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs
I tried fiddling with a bit and decided to get rid of $ sign in this way:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) ( xs )
However, it doesn't even parse (filter applied to too many argumens error). I've read that $ sign is used to simply replace parenthesis and I can't figure out why this simple change of code is bad. Could someone explain it to me?
The infix operator ($) is just "function application". In other words
f x -- and
f $ x
are the same. Since in Haskell parentheses are only used to disambiguate precedence (and for tuple notation and a few other minor places, see comments) we can also write the above in a few other ways
f x
f $ x
(f) x
f (x)
(f) (x) -- and even
(f) $ (x)
In every case, the above expressions denote the same thing: "apply the function f to the argument x".
So why have all this syntax? ($) is useful for two reasons
It has really low precedence so it can stand in for a lot of parentheses sometimes
It's nice to have an explicit name for the action of function application
In the first case, consider the following deeply right-nested function application
f (g (h (i (j x))))
It can be a little difficult to read this and a little difficult to know you have the right number of parentheses. However, it's "just" a bunch of applications so there ought to be a representation of this phrase using ($). Indeed there is
f $ g $ h $ i $ j $ x
Some people find this easier to read. More modern style also incorporates (.) in order to emphasize that the whole left side of this phrase is just a composed pipeline of functions
f . g . h . i . j $ x
And this phrase is, as we saw above, identical to
(f . g . h . i . j) x
which is sometimes nicer to read.
There are also times when we want to be able to pass around the idea of function application. For instance, if we have a list of functions
lof :: [Int -> Int]
lof = [ (+1), (subtract 1), (*2) ]
we might want to map application by a value over them, for instance apply the number 4 to each function
> map (\fun -> fun 4) lof
[ 5, 3, 8 ]
But since this is just function application, we can also use section syntax over ($) to be a bit more explicit
> map ($ 4) lof
[ 5, 3, 8 ]
The operator $ has the lowest priority, so
snd . head . filter (\(k,v) -> key == k) $ xs
is read as
(snd . head . filter (\(k,v) -> key == k)) xs
while your second expression is rather
snd . head . ( filter (\(k,v) -> key == k) xs )
The $ sign isn't magic syntax for replacing parentheses. It's an ordinary infix operator, in every way that an operator like + is.
Putting brackets around a single name like ( xs ) is always equivalent to just xs1. So if that's what the $ did, then you'd get the same error either way.
Try to imagine what would happen if you had some other operator you're familiar with there, such as +:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) + xs
Ignore the fact that + works on numbers so this makes no sense, and just think about the structure of the expression; which terms are being recognised as functions, and which terms are being passed to them as arguments.
In fact, using + there does actually parse and typecheck successfully! (It gives you a function with nonsense type class constraints, but if you fulfill them it does mean something). Lets walk through how the infix operators are resolved:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) + xs
The highest precedence thing is always normal function application (just writing terms next to each other, with no infix operators involved). There's only one example of that here, filter applied to the lambda definition. That gets "resolved", and becomes a single sub-expression as far as parsing the rest of the operators is concerned:
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
in snd . head . fileterExp + xs
The next highest precedence thing is the . operator. We've got several to choose from here, all with the same precedence. The . is right associative, so we take the rightmost one first (but it wouldn't actually change the result whichever one we pick, because the meaning of the . is an associative operation, but the parser has no way of knowing that):
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
dotExp1 = head . filterExp
in snd . dotExp1 + xs
Note that the . grabbed the terms immediately to its left and right. This is why precedence is so important. There's still a . left, which is still higher precedence than +, so it goes next:
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
dotExp1 = head . filterExp
dotExp2 = snd . dotExp1
in dotExp2 + xs
And we're done! + has lowest precedence of the operators here, so it gets its arguments last, and ends up being the top-most call in the whole expression. Note that the + being low precedence prevented the xs being "claimed" as an argument by any of the higher precedence applications to the left. And if any of them had been lower precedence, they would have ended up taking the whole expression dotExp2 + xs as an argument, so they still couldn't have got to xs; putting an infix operator before xs (any infix operator) prevents it from being claimed as an argument by anything to the left.
This is in fact exactly the same way that $ is parsed in this expression, because . and $ happen to have the same relative precedence that . and + have; $ is designed to have extremely low precedence, so it will work this way with almost any other operators involved to the left and right.
If we don't put an infix operator between the filter call and xs, then this is what happens:
let findKey key xs = snd . head . filter (\(k,v) -> key == k) xs
Normal function application goes first. Here we've got 3 terms simply next to each other: filter, (\(k,v) -> key == k), and xs. Function application is left associative, so we take the leftmost pair first:
let findKey key xs
= let filterExp1 = filter (\(k,v) -> key == k)
in snd . head . filterExp1 xs
There's still another normal application left, which is still higher precedence than the ., so we do that:
let findKey key xs
= let filterExp1 = filter (\(k,v) -> key == k)
filterExp2 = filterExp1 xs
in snd . head . filterExp2
Now the first dot:
let findKey key xs
= let filterExp1 = filter (\(k,v) -> key == k)
filterExp2 = filterExp1 xs
dotExp = head . filterExp2
in snd . dotExp
And we're done, the top-most call in the whole expression this time was the left-most . operator. This time xs got sucked in as a second argument to filter; this is sort-of where we want it since filter does take two arguments, but it leaves the result of filter in a function composition chain, and filter applied to two arguments can't return a function. What we wanted was to apply it to one argument to give a function, have that function be part of the function composition chain, and then apply that entire function to xs.
With $ there, the final form mirrors that when we used +:
let findKey key xs
= let filterExp = filter (\(k,v) -> key == k)
dotExp1 = head . filterExp
dotExp2 = snd . dotExp1
in dotExp2 $ xs
It's parsed exactly the same way as when we had +, so the only difference is that where + means "add my left argument to my right argument", $ means "apply my left argument as a function to my right argument". Which is what we wanted to happen! Huzzah!
TLDR: The bad news is that $ doesn't work by just wrapping parentheses; it's more complicated than that. The good news is that if you understand how Haskell resolves expressions involving infix operators, then you understand how $ works. There is nothing at all special about it as far as the language is concerned; it's an ordinary operator you could define yourself if it didn't exist.
1 Parenthesising an operator like (+) also just gives you exactly the same function denoted by +, but now it doesn't have the special infix syntax, so this does affect how things are parsed in this case. Not so with ( xs ) where it's just a name inside.
"$ sign is used to simply replace parenthesis" is pretty much correct – however, it effectively parenthesises everything to both sides! So
snd . head . filter (\(k,v) -> key == k) $ xs
is effectively
( snd . head . filter (\(k,v) -> key == k) ) ( xs )
Of course, the parens around xs are unneeded here (that's an "atom" anyway), so the relevant ones are in this case around the left side. Indeed that happens often in Haskell, because the general philosophy is to think about functions as abstract entities as much as possible, rather than the particular values involved when applying the function to some argument. Your definition could also be written
let findKey key xs' = let filter (\(k,v) -> key == k) $ xs
x0 = head xs'
v0 = snd x0
in v0
That would be extremely explicit, but all those intermediate values aren't really interesting. So we prefer to simply chain the functions together "point-free", with .. That often gets us rid of a lot of boilerplate, indeed for your definition the following can be done:
η-reduction of the xs. That argument just passed on to the chain of functions, so we might as well say "findKey key" is that chain, with whatever argument you supply"!
findKey key = snd . head . filter (\(k,v) -> key == k)
Next, we can avoid this explicit lambda: \(k,v) -> k is simply the fst function. You then need to postcompose comparison with key.
findKey key = snd . head . filter ((key==) . fst)
I'd stop here, since too much point-free is pointless and unreadable. But you could go on: there's new parens now around the argument to key, we can again get rid of those with $. But careful:
"findKey key = snd . head . filter $ (key==) . fst"
is not right, because the $ would again parenthesise both sides, yet (snd . head . filter) is not well-typed. Actually snd . head should only come after both arguments to filter. A possible way to do such a post-post-composition is using the function functor:
findKey key = fmap (snd . head) . filter $ (key==) . fst
...we could go on even further and get rid also of the key variable, but it wouldn't look nice. I think you've got the point...
Other answers have commented in detail on how ($) can replace parentheses, since ($) was defined as an application operator with the right precedence.
I'd like to add that GHC, in order to make it possible to replace parentheses with ($), uses some more magic under the hood than what can be seen from the definition of ($). When higher rank functions are involved, the type system can cope with higher-rank arguments when passed through standard application (as in f x), but not when passed though an application operator (as in f $ x). To overcome this problem, GHC handles ($) in a special way in the type system. Indeed, the following code shows that if we define and use our own application operator ($$), the type system does not apply the same magic handling.
{-# LANGUAGE RankNTypes #-}
-- A higher rank function
higherRank :: (forall a. a -> a -> a) -> (Int, Char)
higherRank f = (f 3 4, f 'a' 'b')
-- Standard application
test0 :: (Int, Char)
test0 = higherRank const -- evaluates to (3,'a')
-- Application via the ($) operator
test1 :: (Int, Char)
test1 = higherRank $ const -- again (3, 'a')
-- A redefinition of ($)
infixr 0 $$
($$) :: (a -> b) -> a -> b
($$) = ($)
test2 :: (Int, Char)
test2 = higherRank $$ const -- Type error (!)
-- Couldn't match expected type `forall a. a -> a -> a'
-- with actual type `a0 -> b0 -> a0'
I have just began recently to learn Haskell, more specifically on the topics of function composition, partial functions, maps, filters and sectioning. On one of the exercises am asked to modify the twoFilters function by using function composition.
I have read a few wikis on . but am having quite a hard time getting it to work correctly. As i understand it, it works by performing the functions b . a on alphabetical order and returning the result. In other words x = foo a and then foo b of x. However after applying several "variations/possibilities" with the bellow two filters functions i cant get it to compile due to errors.
greaterThanOne :: Int -> Bool
greaterThanOne = (>1)
lessThanTen :: Int -> Bool
lessThanTen = (<10)
twoFilters :: [Int] -> [Int]
twoFilters xs= filter lessThanTen (filter greaterThanOne xs)
These two being the unsuccessful attempts I had most confidence on;
twoFilters xs = filter (lessThanTen . greaterThanOne xs)
twoFilters xs = filter (lessThanTen xs . greaterThanOne xs)
Where on the reasoning am I going wrong?
The attempts you were confident about are a simple failure in your logic: the dot operator works like this:
(f.g)(x) = f(g(x))
So, trying to compute an example of 5 gives:
lessThanThen(greaterThanOne(5)) = lessThanTen(True) -- that can't be right, can it???
What you want is a lambda and &&:
filter (\x-> (lessThanThen x) && greaterThanOne(x))
Alternatively, you can use two filters:
filter lessThanTen . filter greaterThanOne $
Enter the wonderful world of Applicative Functors:
import Control.Applicative
greaterThanOne = (>1)
lessThanTen = (<10)
twoFilters = filter ((&&) <$> greaterThanOne <*> lessThanTen)
twoFilters [1,2,3,4,5,6,7,8,9,10]
-- [2,3,4,5,6,7,8,9]
Read Learn you a Haskell - Applicative Functors for a detailed explanation.
You can't compose those two functions like this. f . g works like composition in maths, i.e. is equivalent to f(g(x)). That means the outer function must take an argument of a type that inner function returns, in your case the outer function would have to be Bool -> Bool.
You can write your twoFilters using composition operator like this:
twoFilters = (filter lessThanTen) . (filter greaterThanOne)
(.) expects a function which takes one argument and returns a value, but you pass it a Bool value in:
lessThanTen . greaterThanOne xs
which is wrong.
Here:
lessThanTen xs . greaterThanOne xs
you're trying to compose two Bool values, but you should've composed two functions which return Bool values.
One issue it that function application has highest precedence. So lessThanTen . greaterThanOne xs tries to compose lessThanTen with the result of greaterThanOne xs (which doesn't work to start with, the function works on integers, not on lists thereof). Likewise, lessThanTen xs. greaterThanOne xs tries to compose the results of those function calls (assuming they'd make sense in the first place), not the functions themself.
Another problem is a misunderstanding of . - (f . g) x is equivalent to f (g x), i.e. the result of the first function is the argument for the second. So the type of g must be (a -> b) and the type of f must be (b -> c) (both b are the same type variable!). What you want to apply both functions to the same argument and join the results with &&. There's no existing functions for this as far as I know (at least Hoogle didn't find anything for (a -> Bool) -> (a -> Bool) -> a -> Bool). You'll have to make your own:
both f g x = f x && g x
Alternatively, you coudl just stick to filtering twice (which isn't as bad as it sounds thanks to lazy evaluation) - filter (>1) $ filter (<10) xs.
As i understand it, it works by performing the functions b . a on alphabetical order and returning the result. In other words x = foo a and then foo b of x
This could be written in Haskell as
let x = foo a in
foo b x
(where does foo come from?) but the correct
(b . a) x = let y = a x in
b y
Or, shorter:
(b . a) x = b (a x)
Now, filter lessThanTen (filter greaterThanOne xs) has a similar shape to the right side of this definition, if you remember you could write it as (filter lessThanTen) ((filter greaterThanOne) xs):
((filter lessThanTen) . (filter greaterThanOne)) xs
Presumably what you actually want is filter ??? xs, but that should be enough to go on with.
You have it almost right. I find the easiest way to start learning function composition with . is to use $ first instead.
So you have a list
twoFilters xs = xs
You want to filter by greaterThanOne
twoFilters xs = filter greaterThanOne $ xs
You additionally want to filter by lessThanTen
twoFilters xs = filter lessThanTen $ filter greaterThanOne $ xs
Now move from left to right, replacing all $s with . except for the last $
twoFilters xs = filter lessThanTen . filter greaterThanOne $ xs
You could use parenthesis instead of $ now:
twoFilters xs = (filter lessThanTen . filter greaterThanOne) xs
Or just define the function pointfree:
twoFilters = filter lessThanTen . filter greaterThanOne
The parenthesized version is the most important, I think. It shows that you fuse the two partially-applied functions filter lessThanTen and filter greaterThanOne into one mega-filtering function, with . and then you apply the list to it. You need to parenthesize them because . binds less tightly than function application via whitespace (space can be considered an uber-high-fixity version of $). Remember, when you use ., you are fusing two functions together to form one mega-function.
It is relevant to inspect the type signature of .
(.) :: (b -> c) -> (a -> b) -> a -> c
The functions you feed it have to "line up" with very particular type signatures (they have to be compatible for fusing). But honestly, the key is learning to recognize when function application (with space) is binding more tightly than you intend and messing up the type signatures of functions you are trying to compose. That's how it was for me, anyways.
What is the difference between the dot (.) and the dollar sign ($)?
As I understand it, they are both syntactic sugar for not needing to use parentheses.
The $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.
For example, let's say you've got a line that reads:
putStrLn (show (1 + 1))
If you want to get rid of those parentheses, any of the following lines would also do the same thing:
putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1
The primary purpose of the . operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.
Going back to the same example:
putStrLn (show (1 + 1))
(1 + 1) doesn't have an input, and therefore cannot be used with the . operator.
show can take an Int and return a String.
putStrLn can take a String and return an IO ().
You can chain show to putStrLn like this:
(putStrLn . show) (1 + 1)
If that's too many parentheses for your liking, get rid of them with the $ operator:
putStrLn . show $ 1 + 1
They have different types and different definitions:
infixr 9 .
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(f . g) x = f (g x)
infixr 0 $
($) :: (a -> b) -> a -> b
f $ x = f x
($) is intended to replace normal function application but at a different precedence to help avoid parentheses. (.) is for composing two functions together to make a new function.
In some cases they are interchangeable, but this is not true in general. The typical example where they are is:
f $ g $ h $ x
==>
f . g . h $ x
In other words in a chain of $s, all but the final one can be replaced by .
Also note that ($) is the identity function specialised to function types. The identity function looks like this:
id :: a -> a
id x = x
While ($) looks like this:
($) :: (a -> b) -> (a -> b)
($) = id
Note that I've intentionally added extra parentheses in the type signature.
Uses of ($) can usually be eliminated by adding parenthesis (unless the operator is used in a section). E.g.: f $ g x becomes f (g x).
Uses of (.) are often slightly harder to replace; they usually need a lambda or the introduction of an explicit function parameter. For example:
f = g . h
becomes
f x = (g . h) x
becomes
f x = g (h x)
($) allows functions to be chained together without adding parentheses to control evaluation order:
Prelude> head (tail "asdf")
's'
Prelude> head $ tail "asdf"
's'
The compose operator (.) creates a new function without specifying the arguments:
Prelude> let second x = head $ tail x
Prelude> second "asdf"
's'
Prelude> let second = head . tail
Prelude> second "asdf"
's'
The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:
Prelude> let third x = head $ tail $ tail x
Prelude> map third ["asdf", "qwer", "1234"]
"de3"
If we only use third once, we can avoid naming it by using a lambda:
Prelude> map (\x -> head $ tail $ tail x) ["asdf", "qwer", "1234"]
"de3"
Finally, composition lets us avoid the lambda:
Prelude> map (head . tail . tail) ["asdf", "qwer", "1234"]
"de3"
The short and sweet version:
($) calls the function which is its left-hand argument on the value which is its right-hand argument.
(.) composes the function which is its left-hand argument on the function which is its right-hand argument.
One application that is useful and took me some time to figure out from the very short description at Learn You a Haskell: Since
f $ x = f x
and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4 +) analogous to (++ ", world") "hello".
Why would anyone do this? For lists of functions, for example. Both:
map (++ ", world") ["hello", "goodbye"]
map ($ 3) [(4 +), (3 *)]
are shorter than
map (\x -> x ++ ", world") ["hello", "goodbye"]
map (\f -> f 3) [(4 +), (3 *)]
Obviously, the latter variants would be more readable for most people.
Haskell: difference between . (dot) and $ (dollar sign)
What is the difference between the dot (.) and the dollar sign ($)?. As I understand it, they are both syntactic sugar for not needing to use parentheses.
They are not syntactic sugar for not needing to use parentheses - they are functions, - infixed, thus we may call them operators.
Compose, (.), and when to use it.
(.) is the compose function. So
result = (f . g) x
is the same as building a function that passes the result of its argument passed to g on to f.
h = \x -> f (g x)
result = h x
Use (.) when you don't have the arguments available to pass to the functions you wish to compose.
Right associative apply, ($), and when to use it
($) is a right-associative apply function with low binding precedence. So it merely calculates the things to the right of it first. Thus,
result = f $ g x
is the same as this, procedurally (which matters since Haskell is evaluated lazily, it will begin to evaluate f first):
h = f
g_x = g x
result = h g_x
or more concisely:
result = f (g x)
Use ($) when you have all the variables to evaluate before you apply the preceding function to the result.
We can see this by reading the source for each function.
Read the Source
Here's the source for (.):
-- | Function composition.
{-# INLINE (.) #-}
-- Make sure it has TWO args only on the left, so that it inlines
-- when applied to two functions, even if there is no final argument
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)
And here's the source for ($):
-- | Application operator. This operator is redundant, since ordinary
-- application #(f x)# means the same as #(f '$' x)#. However, '$' has
-- low, right-associative binding precedence, so it sometimes allows
-- parentheses to be omitted; for example:
--
-- > f $ g $ h x = f (g (h x))
--
-- It is also useful in higher-order situations, such as #'map' ('$' 0) xs#,
-- or #'Data.List.zipWith' ('$') fs xs#.
{-# INLINE ($) #-}
($) :: (a -> b) -> a -> b
f $ x = f x
Conclusion
Use composition when you do not need to immediately evaluate the function. Maybe you want to pass the function that results from composition to another function.
Use application when you are supplying all arguments for full evaluation.
So for our example, it would be semantically preferable to do
f $ g x
when we have x (or rather, g's arguments), and do:
f . g
when we don't.
... or you could avoid the . and $ constructions by using pipelining:
third xs = xs |> tail |> tail |> head
That's after you've added in the helper function:
(|>) x y = y x
My rule is simple (I'm beginner too):
do not use . if you want to pass the parameter (call the function), and
do not use $ if there is no parameter yet (compose a function)
That is
show $ head [1, 2]
but never:
show . head [1, 2]
A great way to learn more about anything (any function) is to remember that everything is a function! That general mantra helps, but in specific cases like operators, it helps to remember this little trick:
:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
and
:t ($)
($) :: (a -> b) -> a -> b
Just remember to use :t liberally, and wrap your operators in ()!
All the other answers are pretty good. But there’s an important usability detail about how ghc treats $, that the ghc type checker allows for instatiarion with higher rank/ quantified types. If you look at the type of $ id for example you’ll find it’s gonna take a function whose argument is itself a polymorphic function. Little things like that aren’t given the same flexibility with an equivalent upset operator. (This actually makes me wonder if $! deserves the same treatment or not )
The most important part about $ is that it has the lowest operator precedence.
If you type info you'll see this:
λ> :info ($)
($) :: (a -> b) -> a -> b
-- Defined in ‘GHC.Base’
infixr 0 $
This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.
So then we use it where normal function application or using () doesn't work.
So, for example, this works:
λ> head . sort $ "example"
λ> e
but this does not:
λ> head . sort "example"
because . has lower precedence than sort and the type of (sort "example") is [Char]
λ> :type (sort "example")
(sort "example") :: [Char]
But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .
I think a short example of where you would use . and not $ would help clarify things.
double x = x * 2
triple x = x * 3
times6 = double . triple
:i times6
times6 :: Num c => c -> c
Note that times6 is a function that is created from function composition.