在 Elm 中解码可扩展记录
Decoding extensible records in Elm
我一直在使用 elm (0.18) 中的可扩展记录。我的模型包含这些类型:
type alias Cat c =
{ c
| color : String
, age : Int
, name : String
, breed : String
}
type alias SimpleCat =
Cat {}
type alias FeralCat =
Cat
{ feral : Bool
, spayed : Bool
}
现在我希望能够将这些类型传递给解码器。我通常使用 elm-decode-pipeline 库 "NoRedInk/elm-decode-pipeline": "3.0.0 <= v < 4.0.0"
.
我设置的是这个类型:
catDecoder : Decode.Decoder SimpleCat
catDecoder =
Pipeline.decode SimpleCat
|> Pipeline.required "color" Decode.string
|> Pipeline.required "age" Decode.int
|> Pipeline.required "name" Decode.string
|> Pipeline.required "breed" Decode.string
但是我得到这个错误:
-- NAMING ERROR --------------------------------------------- ./src/Decoders.elm
Cannot find variable `SimpleCat`
141| Pipeline.decode SimpleCat
我的不可扩展类型不会发生这种情况。有没有办法将这些类型与解码器一起使用? (elm-decode-pipeline 首选,但我想知道是否有其他方法)
不幸的是,可扩展记录目前(从 Elm 0.18 开始)不允许使用别名作为构造函数来创建它们。您可以改为编写自己的构造函数:
simpleCatConstructor : String -> Int -> String -> String -> SimpleCat
simpleCatConstructor color age name breed =
{ color = color, age = age, name = name, breed = breed }
然后您可以在对 decode
的调用中替换它:
catDecoder =
Pipeline.decode simpleCatConstructor
|> Pipeline.required "color" Decode.string
...
我一直在使用 elm (0.18) 中的可扩展记录。我的模型包含这些类型:
type alias Cat c =
{ c
| color : String
, age : Int
, name : String
, breed : String
}
type alias SimpleCat =
Cat {}
type alias FeralCat =
Cat
{ feral : Bool
, spayed : Bool
}
现在我希望能够将这些类型传递给解码器。我通常使用 elm-decode-pipeline 库 "NoRedInk/elm-decode-pipeline": "3.0.0 <= v < 4.0.0"
.
我设置的是这个类型:
catDecoder : Decode.Decoder SimpleCat
catDecoder =
Pipeline.decode SimpleCat
|> Pipeline.required "color" Decode.string
|> Pipeline.required "age" Decode.int
|> Pipeline.required "name" Decode.string
|> Pipeline.required "breed" Decode.string
但是我得到这个错误:
-- NAMING ERROR --------------------------------------------- ./src/Decoders.elm
Cannot find variable `SimpleCat`
141| Pipeline.decode SimpleCat
我的不可扩展类型不会发生这种情况。有没有办法将这些类型与解码器一起使用? (elm-decode-pipeline 首选,但我想知道是否有其他方法)
不幸的是,可扩展记录目前(从 Elm 0.18 开始)不允许使用别名作为构造函数来创建它们。您可以改为编写自己的构造函数:
simpleCatConstructor : String -> Int -> String -> String -> SimpleCat
simpleCatConstructor color age name breed =
{ color = color, age = age, name = name, breed = breed }
然后您可以在对 decode
的调用中替换它:
catDecoder =
Pipeline.decode simpleCatConstructor
|> Pipeline.required "color" Decode.string
...