如何 "cast" 联合类型 elm
How to "cast" union types elm
假设我有两个类型别名:
type alias A = {...}
type alias B = {...}
和联合类型
type Content = A | B
和模型类型
type alias Model= {cont : Content, ...}
init : Content -> Model
init cont = {cont = cont, ...}
如何将 A 类型的记录传递给 init.
a : A
a = {...}
init a
抛出以下错误:
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
我会想象 A 是一种 "subtype" 的内容。我不能只写
a:Content
a = {...}
init a
因为有些逻辑是对内容进行案例分析
Elm 的联合类型是所谓的可区分联合(或标记联合)。区分部分是标记或构造函数。在这种情况下,我想你想要:
type Content = TagA A | TagB B
注意第一个大写的名字是tag,其他都是其他类型或者类型变量。
现在您可以:
a : A
a = { ... }
init (TagA a)
在 init
中,您可以通过以下方式区分这两种类型:
init content =
case content of
TagA a -> ...
TagB b -> ...
假设我有两个类型别名:
type alias A = {...}
type alias B = {...}
和联合类型
type Content = A | B
和模型类型
type alias Model= {cont : Content, ...}
init : Content -> Model
init cont = {cont = cont, ...}
如何将 A 类型的记录传递给 init.
a : A
a = {...}
init a
抛出以下错误:
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
我会想象 A 是一种 "subtype" 的内容。我不能只写
a:Content
a = {...}
init a
因为有些逻辑是对内容进行案例分析
Elm 的联合类型是所谓的可区分联合(或标记联合)。区分部分是标记或构造函数。在这种情况下,我想你想要:
type Content = TagA A | TagB B
注意第一个大写的名字是tag,其他都是其他类型或者类型变量。
现在您可以:
a : A
a = { ... }
init (TagA a)
在 init
中,您可以通过以下方式区分这两种类型:
init content =
case content of
TagA a -> ...
TagB b -> ...