haskell高级类型

1, haskell中的问题都可以转换成连续的transformation(划重点!!!)

You can think of transformations as a more abstract level of thinking about functions. When solving problems in Haskell, you can approach them first as a sequence of abstract transformations. For example, say you have a large text document and you need to find all the numbers in that document and then add them all together. How are you going to solve this problem in Haskell? Let’s start with knowing that a document can be represented as a String:

type Document = String

Then you need a function that will break your big String into pieces so you can search for numbers:

Document -> [String]

Next you need to search for numbers. This will take your list of Strings and a function to check whether a String is a number, and will return your numbers:

[String] -> (String -> Bool) -> [String]

Now you have your numbers, but they need to be converted from strings to numbers:

[String] -> [Integer]

Finally, you need to take a list of integers and transform it into a single integer:

[Integer] -> Integer

And you’re finished! By thinking about the types of transformations that you’re going to make, you’ve been able to design your overall program much the same way you design a single function.

2,代数数据类型:用and和or产生组合类型

Algebraic data types are any types that can be made by combining other types. The key to understanding algebraic data types is knowing exactly how to combine other types. Thankfully, there are only two ways. You can combine multiple types with an and (for example, a name is a String and another String), or you can combine types with an or (for example, a Bool is a True data constructor or a False data constructor). Types that are made by combining other types with an and are called product types. Types combined using or are called sum types.

几乎所有编程语言都支持用and组合类型产生新类型,例如:

struct author_name {
  char *first_name;
  char *last_name;
};

struct book {
  author_name author;
  char *isbn;
  char *title;
  int  year_published;
  double price;
};

haskell中与之对应的结构:

data AuthorName = AuthorName String String

data Book = Book {
  author  :: AuthorName, 
  isbn :: String,
  bookTitle :: String, 
  bookYear :: Int, 
  bookPrice :: Double
}

使用or产生新类型:类型层次中的状态差异使用or组合多个数据构造解决,行为差异使用type classes中的函数或独立函数解决

data VinylRecord = VinylRecord {
  artist :: Creator,
  recordTitle :: String, 
  recordYear :: String, 
  recordPrice :: String
}

-- or产生的类型类似java中的继承,
-- StoreItem相当于抽象类,每个数据构造是一个子类
data StoreItem = BookItem Book | RecordItem VinylRecord

-- haskell中的字段名本质上是类型为 “字段所在类型 -> 字段类型” 的函数
-- 所以字段名不能重复(???)
-- 可以通过函数和模式匹配实现公共属性
price :: StoreItem -> Double
price (BookItem book) = bookPrice book
price (RecordItem record) = recordPrice record

3, 组合函数:从右往左依次调用函数

myLast :: [a] -> a
myLast = head . reverse

myMin :: Ord a => [a] -> a
myMin = head . sort

myMax :: Ord a => [a] -> a
myMax = myLast . sort

myAll :: (a -> Bool) -> [a] -> Bool
-- map把list转成[Bool],然后foldr使用&&折叠list
myAll testFunc = (foldr (&&) True) . (map testFunc)

4, guard:模式匹配中的if语句

guards.png

5, 组合类型:实现Semigroup,组合相同类型的的两个实例获得相同类型的新实例,Semigroup需要满足结合性:(a <> b) <> c = a <> (b <> c)

class Semigroup a where
    (<>) :: a -> a -> a

data Color = Red | Yellow | Blue | Green | Purple | Orange | Brown 
    deriving (Show,Eq)

instance Semigroup Color where
    (<>) Red Blue = Purple
    (<>) Blue Red = Purple
    (<>) Yellow Blue = Green
    (<>) Blue Yellow = Green
    (<>) Yellow Red = Orange
    (<>) Red Yellow = Orange
    (<>) a b | a == b = a
                 | all (`elem` [Red,Blue,Purple]) [a,b] = Purple
                 | all (`elem` [Blue,Yellow,Green]) [a,b] = Green 
                 | all (`elem` [Red,Yellow,Orange]) [a,b] = Orange 
                 | otherwise = Brown


-- test
(Green <> Blue) <> Yellow = Green
Green <> (Blue <> Yellow) = Green

6, Monoid:需要一个特殊元素

The only major difference between Semigroup and Monoid is that Monoid requires an identity element for the type. An identity element means that x <> id = x (and id <> x = x). So for addition of integers, the identity element would be 0.

-- mconcat = foldr mappend mempty
-- 所以只需要实现mempty和mappend
class Monoid a where
    mempty :: a
    mappend :: a -> a -> a
    mconcat :: [a] -> a

-- list实现了Monoid和Semigroup
[1,2,3] ++ [] = [1,2,3]
[1,2,3] <> [] = [1,2,3]
[1,2,3] `mappend` mempty = [1,2,3]

Monoid的4个规则:似曾相识的赶脚!!!

 The first is that mappend mempty x is x. Remembering that mappend is the same as (++), and mempty is [] for lists, this intuitively means that

   []  ++ [1,2,3] = [1,2,3]

 The second is just the first with the order reversed: mappend x mempty is x. In list form this is

   [1,2,3] ++ [] = [1,2,3]

 The third is that mappend x (mappend y z) = mappend (mappend x y) z. This is just associativity, and again for lists this seems rather obvious:

   [1] ++ ([2] ++ [3]) = ([1] ++ [2]) ++ [3]

Because this is a Semigroup law, then if mappend is already implemented as <>, this law can be assumed because it’s required by the Semigroup laws.

 The fourth is just our definition of mconcat:

mconcat = foldr mappend mempty

7,参数化类型

参数化类型.png
-- 泛形类型
data Triple a = Triple a a a deriving Show

-- 泛形实例化
type Point3D = Triple Double
aPoint :: Point3D
aPoint = Triple 0.1 53.2 12.3

-- 访问字段
first :: Triple a -> a
first (Triple x _ _) = x
second :: Triple a -> a
second (Triple _ x _ ) = x
third :: Triple a -> a
third (Triple _ _ x) = x

list类型定义:

list.png

自定义list:

-- 自定义list
data List a = Empty | Cons a (List a) deriving Show

-- 跟内置list对比
builtinEx1 :: [Int]
builtinEx1 = 1:2:3:[]
ourListEx1 :: List Int
ourListEx1 = Cons 1 (Cons 2 (Cons 3 Empty))

-- 自定义map
ourMap :: (a -> b) -> List a -> List b
ourMap _ Empty = Empty
ourMap func (Cons a rest)  = Cons (func a) (ourMap func rest)

多类型参数

-- 2-tuple定义
data (,) a b = (,) a b

Kinds: types of types

The type of a type is called its kind. The kind of a type indicates the number of parameters the type takes, which are expressed using an asterisk (*). Types that take no parameters have a kind of *, types that take one parameter have the kind * -> *, types with two parameters have the kind * -> * -> *, and so forth.

kind Int = Int :: *
-- 类型构造有一个泛形参数
kind [] = [] :: * -> *
kind (,) = (,) :: * -> * -> *
-- 泛形参数实例化
kind [Int] = [Int] :: *

Map类型:基于红黑树实现,使用map类型先要限定导入,避免跟prelude冲突

qualified import.png

With your qualified import, every function and type from that module must be prefaced with Map. Map allows you to look up values by using keys. In many other languages, this data type is called Dictionary. The type parameters of Map are the types of the keys and values.

fromList.png
data Organ = Heart | Brain | Kidney | Spleen deriving (Show, Eq)

ids :: [Int]
ids = [2,7,13,14,21,24]

organs :: [Organ]
organs = [Heart,Heart,Brain,Spleen,Spleen,Kidney]

-- zip两个list
organPairs :: [(Int, Organ)]
organPairs = zip ids organs

organCatalog :: Map.Map Int Organ
organCatalog = Map.fromList organPairs

-- lookup
Map.lookup 7 organCatalog = Just Heart

8,Maybe类型:类似java中Optional,强制检查空值

-- Maybe定义
data Maybe a = Nothing | Just a

isSomething :: Maybe Organ -> Bool
isSomething Nothing = False
isSomething (Just _) = True

-- Maybe内置函数
isJust :: Maybe a -> Bool
isNothing :: Maybe a -> Bool 
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容