gpt4 book ai didi

elm - 解码列表时忽略无效项

转载 作者:行者123 更新时间:2023-12-05 09:02:51 25 4
gpt4 key购买 nike

解码列表时是否可以忽略无效项?示例:我有一个模型

type Type
= A
| B

type alias Section =
{ sectionType : Type
, index : Int
}


getTypeFromString : String -> Maybe Type
getTypeFromString input =
case input of
“a” ->
Just A

“b” ->
Just B

_ ->
Nothing

decodeType : Decoder Type
decodeType =
Decode.string
|> Decode.andThen
(\str ->
case getTypeFromString str of
Just sectionType ->
Decode.succeed sectionType

Nothing ->
Decode.fail <| ("Unknown type" ++ str)
)


decodeSection : Decoder Section
decodeSection =
Decode.map2 Section
(Decode.field "type" decodeType)
(Decode.field "index" Decode.int)

如果我解码 JSON

{
"sections": [{type: "A", index: 1}, {type: "invalid-type", index: 2}]
}

我希望我的部分 = [ {type = A, index= 1} ]

最佳答案

通常,处理这些问题的方法是将其解码为表示选项的 Elm 类型,然后使用 map 进行后处理。

所以例如在你的例子中,我会选择这样的东西:

decodeMaybeType : Decoder (Maybe Type)
decodeMaybeType =
Decode.string
|> Decode.map getTypeFromString


decodeMaybeSection : Decoder (Maybe Section)
decodeMaybeSection =
Decode.map2 (\maybeType index -> Maybe.map (\t -> Section t index) maybeType)
(Decode.field "type" decodeMaybeType)
(Decode.field "index" Decode.int)


decodeSections : Decoder (List Section)
decodeSections =
Decode.list decodeMaybeSection
|> Decode.map (List.filterMap identity)

注意:List.filterMap identity 是一个 List (Maybe a) -> List a,它过滤掉 Nothing 并删除Maybe 一气呵成。

关于elm - 解码列表时忽略无效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70736438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com