如何制作带有可选元素的解码器?

ben*_*002 3 decoder elm

我卡与解码应的阵列的译码器[ 9.34958, 48.87733, 1000 ]Point,其中,索引2(仰角)是可选的。

type alias Point =
    { elev : Maybe Float
    , at : Float
    , lng : Float
    }
Run Code Online (Sandbox Code Playgroud)

因此我创建了以下解码器:

fromArrayDecoder : Decoder Point
fromArrayDecoder =
    map3 Point
        (index 2 Decode.float |> Decode.maybe)
        (index 1 Decode.float)
        (index 0 Decode.float)
Run Code Online (Sandbox Code Playgroud)

我现在的问题是,当索引 2 丢失或属于任何类型(如字符串等)时,此解码器会成功。但我希望它仅在 elev 丢失时成功,而不是在类型错误时成功。有没有办法做到这一点?

gle*_*nsl 5

如果“缺失”是指值可以是null,则可以使用nullable代替maybe

fromArrayDecoder : Decoder Point
fromArrayDecoder =
  map3 Point
    (index 2 Decode.float |> Decode.nullable)
    (index 1 Decode.float)
    (index 0 Decode.float)
Run Code Online (Sandbox Code Playgroud)

如果它是 3 元素数组或 2 元素数组,您可以oneOf按顺序尝试多个解码器:

fromTwoArrayDecoder : Decoder Point
fromTwoArrayDecoder =
  map3 (Point Nothing)
    (index 1 Decode.float)
    (index 0 Decode.float)

fromThreeArrayDecoder : Decoder Point
fromThreeArrayDecoder =
  map3 Point
    (index 2 Decode.float |> Decode.map Just)
    (index 1 Decode.float)
    (index 0 Decode.float)

fromArrayDecoder : Decoder Point
fromArrayDecoder =
  oneOf
    [ fromThreeArrayDecoder
    , fromTwoArrayDecoder
    ]
Run Code Online (Sandbox Code Playgroud)

请记住首先尝试 3 元素解码器,因为 2 元素解码器也会在 3 元素数组上成功,但相反不会。