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 have different types and different definitions:
In some cases they are interchangeable, but this is not true in general. The typical example where they are is:
In other words in a chain of
Also note that
Note that I've intentionally added extra parentheses in the type signature.
Hope this helps!
The short and sweet version:
For example, let's say you've got a line that reads:
If you want to get rid of those parentheses, any of the following lines would also do the same thing:
The primary purpose of the
Going back to the same example:
You can chain
If that's too many parentheses for your liking, get rid of them with the
The compose operator
The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:
If we only use third once, we can avoid naming it by using a lambda:
Finally, composition lets us avoid the lambda:
One application that is useful and took me some time to figure out from the very short description at learn you a haskell: Since:
and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write
Why would anyone do this? For lists of functions, for example. Both:
are shorter than
... or you could avoid the
That's after you've added in the helper function:
My rule is simple (I'm beginner too):
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:
Just remember to use
I think a short example of where you would use
They are not syntactic sugar for not needing to use parentheses - they are functions, - infixed, thus we may call them operators.
is the same as building a function that passes the result of its argument passed to
is the same as this, procedurally (which matters since Haskell is evaluated lazily, it will begin to evaluate
or more concisely:
We can see this by reading the source for each function.
Read the Source
Here's the source for
And here's the source for
When to use:
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
when we have
when we don't.