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语句

haskell高级类型_第1张图片
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,参数化类型

haskell高级类型_第2张图片
参数化类型.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类型定义:

haskell高级类型_第3张图片
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冲突

haskell高级类型_第4张图片
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.

haskell高级类型_第5张图片
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 

你可能感兴趣的:(haskell高级类型)