haskell筆記(1)- data type

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

newtypedata高效,因?yàn)閐ata要重新包裝,而newtype只包含一個(gè)值,只是值的類(lèi)型被重新定義了一下

data ZipList a = ZipList { ZipList :: [a]}
newtype ZipList a = ZipList { ZipList :: [a]}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容