data 定義
we can use the same name for data type and value constructor, This has no special meaning, like Person in the following:
data Point = Point Float Float deriving(Show)
Value constructors are actually **functions that ultimately return a value of a data type. **
record syntax
當(dāng)一種data type包含很多字段的時(shí)候,用舊的方式定義會(huì)完全搞不懂什么是什么,recoard syntax省事多了
并且這樣會(huì)聲稱(chēng)字段對(duì)應(yīng)的方法 model, year
>> data Car = Car { model :: String, year :: int } deriving Show
>> car = Car { model = "Honda", year = 1988}
>> model car
Honda
>> car
Car { model = "Honda", year = 1988}
type parameter and type constructor
給data type加參數(shù)可以生成不同的data type,Maybe可以生成Maybe [Char] Maybe Int之類(lèi)
data Maybe a = Nothing | Just a
-- a 只是定義了類(lèi)型, 跟參數(shù)完全沒(méi)關(guān)系
-- ZipList Int之類(lèi)的是個(gè)整體,而不是真的有具體的值ZipList 1
data ZipList a = ZipList { getZipList :: [a] }
newtype
newtype比data高效,因?yàn)閐ata要重新包裝,而newtype只包含一個(gè)值,只是值的類(lèi)型被重新定義了一下
data ZipList a = ZipList { ZipList :: [a]}
newtype ZipList a = ZipList { ZipList :: [a]}