Devs.tw 是讓工程師寫筆記、網誌的平台。歡迎您隨手紀錄、寫作,方便日後搜尋!
大部份語言中 這種 data structure attribute 的順序沒有意義
比方說 python 的 dictionary
但 elm 好像不是這樣
舉例
type alias User =
{ id : Int
, name : String
, email : String
}
userDecoder : Decoder User
userDecoder =
Decode.succeed User
|> required "id" int
|> required "name" string
|> required "email" string
他是從 json string 中取值,依序賦予 record 各 attribute
type alias User =
{ id : Int
, email : String
}
userDecoder : Decoder User
userDecoder =
let
-- toDecoder gets run *after* all the
-- (|> required ...) steps are done.
toDecoder : Int -> String -> Int -> Decoder User
toDecoder id email version =
if version > 2 then
Decode.succeed (User id email)
else
fail "This JSON is from a deprecated source. Please upgrade!"
in
Decode.succeed toDecoder
|> required "id" int
|> required "email" string
|> required "version" int
-- version is part of toDecoder,
|> resolve
注意看 toDecoder 的 type
正是依照 record attribute 的順序呢
When you create a type alias specifically for a record, it also generates a record constructor. So if we define a User type alias, we can start building records like this:
> type alias User = { name : String, age : Int }
> User
<function> : String -> Int -> User
> User "Sue" 58
{ name = "Sue", age = 58 } : User
> User "Tom" 31
{ name = "Tom", age = 31 } : User
確實就是依序傳進參數!