尤川豪   ·  2年前
445 貼文  ·  275 留言

Elm record 的順序是有意義的

大部份語言中 這種 data structure attribute 的順序沒有意義

比方說 python 的 dictionary

但 elm 好像不是這樣

舉例

1.

https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest/Json-Decode-Pipeline#required

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

2.

https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest/Json-Decode-Pipeline#resolve

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 的順序呢

3. 原來,原因在這邊 - Record Constructors

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

確實就是依序傳進參數!

  分享   共 723 次點閱
共有 0 則留言
還沒有人留言。歡迎分享您的觀點、或是疑問。
您的留言
尤川豪
445 貼文  ·  275 留言

Devs.tw 是讓工程師寫筆記、網誌的平台。隨手紀錄、寫作,方便日後搜尋!

歡迎您一起加入寫作與分享的行列!

查看所有文章