読者です 読者をやめる 読者になる 読者になる

by shigemk2

当面は技術的なことしか書かない

レコード構文

Haskell
data Person = Person String String Int Float String String
     deriving (Show)
-- *Main> let guy = Person "Buddy" "Finklestein" 43 184.2 "526-2928" "Chocolate"
-- *Main> guy
-- Person "Buddy" "Finklestein" 43 184.2 "526-2928" "Chocolate"

firstName :: Person -> String
firstName (Person firstname _ _ _ _ _) = firstname

lastName :: Person -> String
lastName (Person _ lastname _ _ _ _) = lastname

age :: Person -> Int
age (Person _ _ age _ _ _) = age

height :: Person -> Float
height (Person _ _ _ height _ _) = height

phoneNumber :: Person -> String
phoneNumber (Person _ _ _ _ number _) = number

flavor :: Person -> String
flavor (Person _ _ _ _ _ flavor) = flavor

-- ああ、なんという泥臭い方法なのでしょう
-- *Main> let guy = Person "Buddy" "Finklestein" 43 184.2 "526-2928" "Chocolate"
-- *Main> firstName guy
-- "Buddy"
-- *Main> height guy
-- 184.2
-- *Main> flavor guy
-- "Chocolate"

-- こんなポンコツななことやらなくても、レコード構文というものを使えば、いいんだよ
-- こんな風にしてレコード構文を作ることが出来るお
data Person = Person { firstName :: String
                     , lastName :: String
                     , age :: Int
                     , height :: Float
                     , phoneNumber :: String
                     , flavor :: String } deriving (Show)

-- *Main> :t flavor
-- flavor :: Person -> String
-- *Main> :t firstName
-- firstName :: Person -> String

data Car = Car { company :: String
               , model :: String
               , year :: Int
               } deriving (Show)

-- *Main> Car {company="Ford", model="Mustang", year=1967 }
-- Car {company = "Ford", model = "Mustang", year = 1967}
-- 順番はどうでもいいけど
-- *Main> Car { year=2012 , company="Nissan", model="March" }
-- Car {company = "Nissan", model = "March", year = 2012}

-- フィールドは全て埋める必要があるお
-- *Main> Car { company="Nissan", model="March" }
-- <interactive>:44:1:
--     Warning: Fields of `Car' not initialised: year
--     In the expression: Car {company = "Nissan", model = "March"}
--     In an equation for `it':
--         it = Car {company = "Nissan", model = "March"}