operatorselmcolon-equals

What exactly does the := operator do in Elm?


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


Solution

  • 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.