In the following code taken from Elm Form Example, line 122, what does the <<
operator mean?
Field.field Field.defaultStyle (Signal.send updat
<< is a function composition - returns function.
Composition creates a pipe of computations, chain of functions. This pipe waits for input, and when provided, first function starts computation, sends output to next etc.
import Html
add x y =
Debug.log "x" x + Debug.log "y" y
add9 =
add 4 << add 5
main =
Html.text <| toString <| add9 2
Note: In the above example I use partial application. It means that I don't provide all parameters to function and as a result I get function.
If you run above example in web browser and look at the console output, you will see:
x: 5
y: 2
x: 4
y: 7
If we write it as math operations it will look like this:
4 + (5 + 2)
4 + 7
Note: We can also use forward version >>
.
Looking at signature of this operator:
(<<) : (b -> c) -> (a -> b) -> a -> c
For <<
operator, there is a function b -> c
as the first parameter, and a function a -> b
as the second:
(b -> c) << (a -> b)
But there is also a third parameter a
. Because ->
is right-associative, then
(<<) : (b -> c) -> (a -> b) -> a -> c
is equivalent to:
(<<) : (b -> c) -> (a -> b) -> (a -> c)
.
So that <<
returns function a -> c
.
In programming languages, the associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses; i.e. in what order each operator is evaluated:
a = b = c
is parsed as a = (b = c)
Here I use <<
as infix operator, but we can also use it as a prefix operator enclosing it with parenthesis: (<<) (b -> c) (a -> b)
or (<|) (add 4) (add 5)
.
elm < 0.18 used to let you take normal functions and use them as infix operators.
<|
operator<| is a function application - returns value
We basically use it instead of parentheses.
text (something ++ something)
can be written as
text <| something ++ something
So looking at signature of this operator:
(<|) : (a -> b) -> a -> b
we can see that for <|
operator, there is a function a -> b
as the first parameter, and value a
as the second:
(a -> b) <| a
and it returns b
.
We can get the same value with function application <|
:
v1 = add 4 <| add 5 <| 4
v2 = (add 4 << add 5) 4
|>
.<|
and <<