日志

记录是一组键值对。

greeter =
    { isMorning: True
    , greeting: "Good morning!"
    }

通过不存在的密钥访问值是不可能的。

动态修改 Record 的结构是不可能的。

记录仅允许你通过常量键更新值。

访问值

使用动态密钥无法访问值以防止可能的运行时错误:

isMorningKeyName =
    "isMorning "

greeter[isMorningKeyName] -- Compiler error
greeter.isMorning -- True

访问该值的替代语法允许你在通过 Record 记录时提取值:

greeter
    |> .greeting
    |> (++) " Have a nice day!" -- "Good morning! Have a nice day!"

扩展类型

有时你需要参数的签名来约束传递给函数的记录类型。扩展记录类型使得超类型的概念变得不必要。以下示例显示了如何实现此概念:

type alias Person =
    { name : String
    }

type alias Animal =
    { name : String
    }

peter : Person
peter =
    { name = "Peter" }

dog : Animal
dog =
    { name = "Dog" }

getName : { a | name : String } -> String
getName livingThing =
    livingThing.name

bothNames : String
bothNames =
    getName peter ++ " " ++ getName dog

我们甚至可以进一步扩展记录并执行以下操作:

type alias Named a = { a | name : String }
type alias Totalled a = { a | total : Int }

totallyNamed : Named ( Totalled { age : Int })
totallyNamed =
  { name = "Peter Pan"
  , total = 1337
  , age = 14
  }

我们现在有办法在函数中传递这些部分类型:

changeName : Named a -> String -> Named a
changeName a newName =
  { a | name = newName }
  
cptHook = changeName totallyNamed "Cpt. Hook" |> Debug.log "who?"

更新值

Elm 有一个特殊的 Record 更新语法:

model =
    { id: 1
    , score: 0
    , name: "John Doe"
    }

update model =
    { model
       | score = model.score + 100
       | name = "John Johnson"
    }