Elm Pattern matching on Generic Data Structure
给出以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | type Msg = NoOp | UpdateField ReqRes type ReqRes a = Request a | Response (Result Http.Error Bool) update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of UpdateField reqres -> case reqres of Request a -> -- Do stuff Response result -> -- Do stuff _ -> -- Do stuff |
如您所见,我有一个名为UpdateField的消息,它采用UnionType ReqRes。到现在为止还挺好。但是联合类型具有通用数据结构(或包含类型变量...这是否意味着相同的意思?)。
我的问题是现在,我不知道如何对此进行图案匹配。
编译器告诉我这个错误:
... Problem in this pattern match
The pattern matches things of type:
1 ReqRes aBut the values it will actually be trying to match here are:
1 ReqRes
如果在
类似地,如果存在类型
因此,这是您的代码正常工作所需的更改:
1 2 3 4 5 6 7 8 9 | type Msg = NoOp | UpdateField ReqRes ... becomes... type Msg a = NoOp | UpdateField (ReqRes a) |
和
1 2 3 4 5 | update : Msg -> Model -> (Model, Cmd Msg) ... becomes... update : Msg a -> Model -> (Model, Cmd (Msg a)) |