HaskellのRecord
HaskellのRecord
code:hs
data User = User
{ userId :: Int
, name :: String
, age :: Int
}
let user = User { userId = 3, name = "tarou", age = 28 }
name user -- > "tarou"
// update
let changeName = user { name = "hanako" } -- > { userId = 3, name = "hanako", age = 28}
Record型を定義すると同時に色々なものが暗黙的に導入される
code:hs
data Foo = FooC { baz :: Int }
このような型を定義すると以下のものが導入される
① 型Foo
② Constructor Fooc
③ 構築の為のbaz
code:hs
foo1 = Foo { baz = 1 }
④ 更新の為のbaz
code:hs
update :: Foo -> Int -> Foo
update foo newId = foo { baz = newId }
これって、言語的には③と同じなのかなmrsekut.icon
⑤パターンマッチの為のbaz
code:hs
patt = \case
Foo { baz = 1 } -> ...
...
⑥ getterの為のbaz
code:hs
get :: Foo -> Int
get = baz