What exactly does the := operator do in Elm?
Asked Answered
R

3

7

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

Rufford answered 3/4, 2016 at 7:22 Comment(2)
Please explain what you do not understand or what is not working. I am voting to close this question as Unclear what you are askingDandiprat
Wow, after all the replies It's all clear. Many thanks to everyone. I could not understand that this operator is specific for Json.Decode package, I thought it origins from core.Rufford
W
14

Please note that (:=) is removed from Json.Decode starting from 0.18.0

Infix operators

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.

Native Code

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);
  };
}

TL;DR

(:=) 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.

Wrongheaded answered 3/4, 2016 at 18:18 Comment(0)
B
5

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.

Barmecidal answered 3/4, 2016 at 10:10 Comment(0)
C
3

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
Cow answered 3/4, 2016 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.