How to "pour" elm union types

Suppose I have two types of aliases:

type alias A = {...}
type alias B = {...}

and type of association

type Content = A | B

and model type

type alias Model= {cont : Content, ...}

init : Content -> Model
init cont = {cont = cont, ...}

How to pass type A record to init.

a : A
a = {...}
init a 

produces the following error:

Detected errors in 1 module.
## ERRORS in Main.elm ##########################################################

-- TYPE MISMATCH ------------------------------------------------------ Main.elm

The 1st argument to function `init` has an unexpected type.

78|               init e
                       ^
As I infer the type of values flowing through your program, I see a conflict
between these two types:

    Content

    A

I would suggest that A is a kind of "subtype" of Content. I can't just write

a:Content
a = {...}
init a

because part of the logic analyzes the content case

+4
source share
1 answer

Elm union types are the so-called discriminated unions (or labeled unions). The discriminatory part is a tag or constructor. In this case, I think you want:

type Content = TagA A | TagB B

Note that the first uppercase name is the tag, and everything else is other types or type variables.

Now you can do:

a : A
a = { ... }
init (TagA a)

Inside inityou can distinguish two types:

init content =
  case content of
    TagA a -> ...
    TagB b -> ...
+7
source

Source: https://habr.com/ru/post/1618618/


All Articles