Json 如何将Result.withDefault函数应用于生成结果的函数
我有一个解码JSON的函数Json 如何将Result.withDefault函数应用于生成结果的函数,json,functional-programming,decode,elm,Json,Functional Programming,Decode,Elm,我有一个解码JSON的函数 type alias Item = { title : String , description : String , price : Float , imageUrl : String } itemDecoder : Json.Decode.Decoder Item itemDecoder = D.map4 ItemData (D.field "title" D.string)
type alias Item =
{ title : String
, description : String
, price : Float
, imageUrl : String
}
itemDecoder : Json.Decode.Decoder Item
itemDecoder =
D.map4 ItemData
(D.field "title" D.string)
(D.field "description" D.string)
(D.field "price" D.float)
(D.field "imageUrl" D.string)
decodeItem : Json.Decode.Value -> Item
decodeItem =
Json.Decode.decodeValue itemDecoder
我从编译器得到的错误是decodeItem生成
Json.Decode.Value->Result Json.Decode.Error项
而不是
Json.Decode.Value->Item
如何使用Result.withDefault包装decodeItem的输出,使其生成有效项或返回空项。空项将是结果的第一个参数。默认情况下。如果您有一个返回空项的函数,例如emptyItem,则只需执行您描述的步骤: 使用Result.withDefault包装decodeItem的输出 空项将是Result.withDefault的第一个参数 因此:
decodeItem : D.Value -> Item
decodeItem value =
Result.withDefault emptyItem (D.decodeValue itemDecoder value)
emptyItem可以是返回具有默认值的项记录的函数,例如:
emptyItem : Item
emptyItem = Item "" "" 0 ""
或者一些合理的默认值,对您有意义如果您有一个返回空项的函数,例如emptyItem,您只需要执行您描述的步骤: 使用Result.withDefault包装decodeItem的输出 空项将是Result.withDefault的第一个参数 因此:
decodeItem : D.Value -> Item
decodeItem value =
Result.withDefault emptyItem (D.decodeValue itemDecoder value)
emptyItem可以是返回具有默认值的项记录的函数,例如:
emptyItem : Item
emptyItem = Item "" "" 0 ""
或者一些合理的默认值,对您有意义明白了,谢谢!我觉得我遗漏了一些东西,因为与javascript相比,代码太少了!明白了,谢谢!我觉得我遗漏了一些东西,因为与javascript相比,代码太少了!