Here is an unclear example from docs, using this operator: http://package.elm-lang.org/packages/elm-lang/core/3.0.0/Json-Decode#at
Please note that (:=) is removed from Json.Decode starting from 0.18.0
In Elm, you can define custom infix operators, the purpose of their existence is for providing a more readable version of the code. Ironically, when you're not familiar with the concept, it does the opposite.
(:=) is a custom infix operator, provided by Json.Decode package.
Please consider the following example of a custom infix operator:
import Html exposing (text)
(<|>) : String -> String -> String
(<|>) beginning end =
beginning ++ "Bar" ++ end
main =
text ("Foo" <|> "Buz") -- "FooBarBuz"
It is highly recommended to avoid usage of custom infix operators.
Let's get back to (:=) operator.
The type definition for it looks like (:=) : String -> Decoder a -> Decoder a
, which means, that we have to pass a String and a Decoder, from the list of available Decoder Primitives and reruns a new decoder, with a string key mapped to it.
In JavaScript world, Decoders are callback functions that do type checking.
For example, here is a Decoder String Primitive:
function decodeString(value) {
if (typeof value === 'string' || value instanceof String) {
return value;
}
crash('a String', value);
}
And here's a JavaScript equivalent of (:=) operator:
function decodeField(field, decoder) {
return function(value) {
var subValue = value[field];
if (subValue !== undefined) {
return decoder(subValue);
}
crash("an object with field '" + field + "'", value);
};
}
(:=) maps a string key to a callback (it's not exactly a callback, but that's the closest you could think of), which will check the type of the value in JavaScript object, when you convert it into Elm value.
It creates a decoder for the given key in a json string.
"name" := string
Creates a decoder that extracts the value in "name" and passes it to the string
decoder.
It takes a key for the dictionary you're operating on and attempts to decode what's found there with a decoder, such as any of the built in ones or even your own custom one.
It's essentially a single access at
.
at ["name"] string
Is equal to:
"name" := string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With