ITC*_*hap 1 pattern-matching elm
我有一个更新功能,如:
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
NewImages (Ok images) ->
({model|images = images}, Cmd.none)
NewImages (Err error) ->
myFunction model
NewUsers (Ok users) ->
({model|users = users}, Cmd.none)
NewUsers (Err error) ->
myFunction model
[...]
Run Code Online (Sandbox Code Playgroud)
和myFunction每次我得到HTTP.Error时我想调用的函数.
显然,_不能用来匹配像中的模式的开头
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
NewImages (Ok images) ->
({model|images = images}, Cmd.none)
NewUsers (Ok users) ->
({model|users = users}, Cmd.none)
_ (Err error) ->
myFunction model
[...]
Run Code Online (Sandbox Code Playgroud)
那么,在我的更新函数中匹配所有Http.Error的正确方法是什么?
我不知道如何匹配Http.Error更新功能中的所有s,但您可以将所有Http.Errors 映射到专用消息.
type Msg
= NewImages (List String)
| ...
| HttpError Http.Error
send : (a -> Msg) -> Request Http.Error a -> Cmd Msg
send tagger request =
let
makeMsg result =
case result of
Ok a ->
tagger a
Err error ->
HttpError error
in
Http.send makeMsg request
-- and make an HTTP request like:
send NewImages request
Run Code Online (Sandbox Code Playgroud)
然后,您可以匹配所有HTTP错误.
update msg model =
case msg of
NewImages images ->
({ model | images = images }, Cmd.none)
...
HttpError error ->
myFunction error
Run Code Online (Sandbox Code Playgroud)