LoginSignup
1
0

More than 3 years have passed since last update.

Haskellとレコード構文でゲッターを実装する

Posted at

はじめに

いなたつアドカレの十六日目の記事です。

びふぉー


data Student = Student String String Int -- なまえ, 学籍番号, 学年

getName :: Student -> String
getName (Student name _ _) = name

nameのゲーッターを作成しています。
これを全フィールド分かくのはとても無駄だし、引数の順番と中身がわかりにくいです。

あふたー

data Student = Student { name : String,
                       s_id : String,
                       grade : Int}

test_student :: Student
test_student = Student {name = "inatatsu", s_id = "18-0015", grade = 2}

このようにStudent型をレコード構文を用いて実装することで、Student型の可読性が上がります。
さらに、フィールドの名前を指定できるため、引数の順番を覚える必要性がなくなります。

そして、レコード構文では、各フィールドへのゲッターが自動で生成されます。

まとめ

Haskellをすこれよ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0