Haskell语言学习笔记(16)Alternative

来源:互联网 发布:淘宝没有销量 编辑:程序博客网 时间:2024/05/29 17:16

Alternative

class Applicative f => Alternative f where    empty :: f a    (<|>) :: f a -> f a -> f a
Alternative(选择)是个类型类。
what does Haskell's <|> operator do?

Alternative 的法则

empty <|> u  =  uu <|> empty  =  uu <|> (v <|> w)  =  (u <|> v) <|> w

[] 是 Alternative

instance Alternative [] where    empty = []    (<|>) = (++)
Prelude Control.Applicative> [1] <|> [2][1,2]Prelude Control.Applicative> [1,2] <|> empty[1,2]

Maybe 是 Alternative

instance Alternative Maybe where    empty = Nothing    Nothing <|> r = r    l       <|> _ = l
Prelude Control.Applicative> Just 2 <|> Just 3Just 2Prelude Control.Applicative> Nothing <|> Just 3Just 3Prelude Control.Applicative> foldl1 (<|>) [Nothing, Just 5, Just 3]Just 5Prelude Control.Applicative> foldl (<|>) empty [Nothing, Just 5, Just 3]Just 5

asum 函数

asum :: (Foldable t, Alternative f) => t (f a) -> f aasum = foldr (<|>) empty
Prelude Data.Foldable> asum [Nothing, Just 5, Just 3]Just 5Prelude Data.Foldable> asum [[2],[3],[4,5]][2,3,4,5]
0 0
原创粉丝点击