Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 871
Fake Fish Avatar asked Apr 03 '16 07:04

Fake Fish


3 Answers

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.

like image 144
halfzebra Avatar answered Nov 19 '22 20:11

halfzebra


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.

like image 30
Sebastian Avatar answered Nov 19 '22 19:11

Sebastian


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
like image 3
Charles Maria Avatar answered Nov 19 '22 18:11

Charles Maria