Drkcore

25 07 2012 Haskell Tweet

Haskellのレコード構文

レコード構文の話

data Test = TS {vars::[Int], others::[Int]} deriving Show

既にあるデータに対しても利用できて、もとのデータの値を一部だけ変更した新しいデータが作られる。

*Main> let ts = TS {vars=[], others=[1..10]}
*Main> ts
TS {vars = [], others = [1,2,3,4,5,6,7,8,9,10]}
*Main> ts {vars=[1,2,3]}
TS {vars = [1,2,3], others = [1,2,3,4,5,6,7,8,9,10]}

知らなかった。

それから、データコンストラクタが異なっていれば同じフィールド名を付けられる。

data AnotherTest = TS1 {vars::[Int], others::[Int]} 
                 | TS2 {vars::[Int], others::[Int]} 
                 deriving Show

othersを変更してみる

*Main> let ts1 = TS1{vars=[1..3],others=[]}
*Main> let ts2 = TS2{vars=[1..3],others=[]}
*Main> ts1 {others=[1]}
TS1 {vars = [1,2,3], others = [1]}
*Main> ts2 {others=[2]}
TS2 {vars = [1,2,3], others = [2]}

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021