SUCC函数
product函数
定义:
product :: [Int] -> Int
product [] = 1
product (a:ax) = a * (product ax)
lists
只能用:从前面加
tail返回值是个list
null函数的功能如下
!! 函数返回index
take 和drop函数
concat
concat输入列表的列表,并返回列表相加的结果
length和reverse和lines的用法
reverse是生成一个新数组,不是改变原有的
Tuples元组
lists和tuples的不同
fst and snd
fst提取第一个,snd提取第二个
循环语句
if else
whatIs name =
if name=="Fido" then "Fido is a dog"
else if name=="Tiddles" then "Tiddles is a cat"
else "I don't know what "++name++" is"
whatIs "Fido"
guards
whatIs' name
| name == "Fido" = "Fido is a dog"
| name == "Tiddles" = "Tiddles is a cat"
| otherwise = "I don't know what " ++ name ++ " is"
case
whatIs'' name =
case name == "Fido" of
True -> "Fido is a dog"
False ->
case name == "Tiddles" of
True -> "Tiddles is a cat"
False -> "I don't know what " ++ name ++ " is"
if… then … else
check myname name =
if name == myname then "hello" else "sorry, wrong person"
Pattern Matching
定义一个nonEmpty函数
cond 函数
cond类似于自定义函数
关于type的问题
Enumerated Types枚举类型
类似常量
Parametrised Algebraic Types参数化枚举类型
type VCard = [CardAttribute]
data CardAttribute = NAMEAttribute String
| TELAttribute String
| EMAILLAttribute String
deriving (Eq, Show)
- 全部以大写开头
- 可以有多个参数
- 不是真正的函数,因为他们只是打包了包含在其参数中的数据
Defining Functions by Pattern-Matching通过模式匹配定义函数
data Position = Point Int Int
deriving (Eq,Show)
data Direction = North | South | East | West
step :: Direction -> Position -> Position
step North (Point x y) = Point x (y+1)
step South (Point x y) = Point x (y-1)
step East (Point x y) = Point (x+1) y
step West (Point x y) = Point (x-1) y
JSON
递归
- Returns
True
if the list contains0
andFalse
otherwise.
containsZero :: [Int] -> Bool
containsZero [] = False
containsZero (x:xs)
| 0 == x = True
| otherwise = containsZero(xs)
- The function
even
tests whether a number is even.
containsEven :: [Int] -> Bool
containsEven [] = False
containsEven (x:xs)
| even x = True
| otherwise = containsEven(xs)
- Returns the sublist of non-zero elements
nonZeroElements :: [Int] -> [Int]
nonZeroElements [] = []
nonZeroElements (x:xs)
| x == 0 = nonZeroElements(xs)
| otherwise = x:(nonZeroElements(xs))
- Returns the sublist of even elements
evenElements :: [Int] -> [Int]
evenElements [] = []
evenElements (x:xs)
| even x = x:(evenElements(xs))
|otherwise = evenElements(xs)
- Returns the result of adding 1 to each element of the list
mapInc :: [Int] -> [Int]
mapInc [] = []
mapInc (x:xs) = (x+1):mapInc(xs)
- 遍历一次列表并返回包含其长度和总和的元组
lengthAndSum :: [Int] -> (Int, Int)
lengthAndSum [] = (0, 0)
lengthAndSum (x:xs) = let (l, s) = lengthAndSum xs in (l+1, s+x)
let…in的用法
let variable = expression in expression
data.tree结构
Data.Tree 是一种非空(存在根节点),可以有无限分支,每个节点均可有多路分支的Tree类型
data Tree = Empty | Leaf Int | Node Int Tree Tree
deriving (Eq, Show)
data Tree a = Leaf a | Branch [Tree a]
分支包含树的列表,因此可能包含任意数量的子树
data Tree a = Leaf a | Branch (Tree a) (Tree a)
这是明确的两个子树,因此是二叉树
附加函数 Additional parameters
- counts the number of time n occurs in the list xs 统计n在xs中出现的次数
countN :: Int -> [Int] -> Int
-- countN n xs counts the number of time n occurs in the list xs
countN n [] = 0
countN n (x:xs) = if x==n then 1+(countN n xs) else (countN n xs)
countGreaterN n xs
counts the number of elements of the listxs
greater thann
countGreaterN :: Int -> [Int] -> Int
countGreaterN n [] = 0
countGreaterN n (x:xs) = if x>n then 1+(countGreaterN n xs) else (countGreaterN n xs)
mapAddN n xs
returns the result of addingn
to all the elements of the listxs
mapAddN :: Int -> [Int] -> [Int]
mapAddN n [] = []
mapAddN n (x:xs) = n+x:mapAddN n xs
mapTimesN n xs
returns the result of multiplying all the elements of the listxs
byn
mapTimesN::Int->[Int]->[Int]
mapTimesN n [] = []
mapTimesN n (x:xs) = n*x:mapTimesN n xs
mapEqualsN n xs
returns the list of Booleans resulting from comparing each element of the listxs
ton
mapEqualsN :: Int -> [Int] -> [Bool]
mapEqualsN n [] = []
mapEqualsN n (x:xs) = (n==x):mapEqualsN n xs
mapF f xs
returns the list resulting from applying the functionf
to each element of the listxs
mapF::(a->b)->[a]->[b]
mapF f [] = []
mapF f (x:xs) = (f x):mapF f xs
filterP p xs
returns the sublist ofxs
containing those elementsx
for whichp x
isTrue
filterP :: (a -> Bool) -> [a] -> [a]
filterP p [] = []
filterP p (x:xs) | p x = x : (filterP p xs)
| otherwise = filterP p xs
anyP p xs
returnsTrue
if some element of the listxs
satisfies the predicatep
andFalse
otherwise
anyP :: (a -> Bool) -> [a] -> Bool
anyP p [] = False
anyP p (x:xs) = if p x then True else anyP p xs
Additional parameters (varying in the recursive call在递归调用中不同)
取xs的前n个元素
take' :: Int -> [a] -> [a]
-- take' n xs takes the first n elements of xs
take' n [] = []
take' n (a:as) = if (n<=0) then [] else a:(take'(n-1) as)
drop' n xs
drops the firstn
elements ofxs
drop' :: Int -> [a] -> [a]
drop' n [] = []
drop' 0 xs = xs
drop' n (x:xs) = drop' (n-1) xs
- 遇到第一个不满足元素就停止
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p [] = []
takeWhile' p (x:xs) | p x = x:(takeWhile' p xs)
| otherwise =[]
- 满足就放前面,不满足就放后面
break' :: (a -> Bool) -> [a] -> ([a],[a])
break' p [] = ([], [])
break' p (x:xs) = if p x then ([], x:xs) else (x:l, r)
where
(l, r) = break' p xs
break' (=='c') "abcdef"
Structural recursion on trees树的结构递归
size t
returns the total number of Nodes and Leaves in the treet
(not counting Empty’s)
size :: Tree -> Int
size Empty = 0
size (Leaf _) = 1
size (Node n l r) = 1 + size l + size r
sum函数
定义如下
sum [] = 0
sum (n:ns) = n + sum ns --递归定义
foldl和foldr
let a =[1,2,3]
foldl (+) 1 a
foldr (+) 1 a
let b = 2
foldl (^) b a -- f (f (f b 1) 2) 3
foldr (^) b a -- f 1 (f 2 (f 3 b))
map函数
map接收一个函数和一个List,返回另一个List
map (\x -> x + 2) [1,2,3]
返回[3,4,5]
filter 函数
高阶函数(High-order functions)
higher-order function是指可以操作函数的函数,函数可以作为参数,也可以作为返回结果
Lambda表达式
lambda就是编写匿名的函数
plusOne = \x -> x+1
plus = \ (x,y) -> x+y
plus (3,4)
结果为7
以下三种写法结果相等
1
isTELLine line = take 3 line == "TEL"
getTELFromLine line = tail $ dropWhile (/= ':') line
getTELFromVcard cards = map getTELFromLine $ filter isTELLine $ lines cards
2
isTELLine line = take 3 line == "TEL"
getTELFromLine line = tail $ dropWhile (/= ':') line
getTELFromVcard' card = map getTELFromLine $ filter isTELLine $ lines card
3
getTELFromVcard'' = map (tail.dropWhile (/= ':')) . filter ((=="TEL").(take 3)) . lines
1和2是一样的
Curried functions
Haskell里所有的函数都只有一个参数,例如max 函数其实可以写成 (max x) y
它是可以省略参数的
map (*3) [1,2,3] -- map所有元素 *2 的操作
filter (>2) [2,3,4,5] -- 过滤 >2的元素
'f' `elem` ['a' .. 'g'] -- 是否包含'f'
前缀模式与中缀模式
haskell中的函数默认都是前缀模式,但几乎所有拥有两个参数的函数,只需要将函数名反引号包起来就可变成中缀模式
Currying去掉多余参数
sum' xs = foldl (+) 0 xs
sum'' = foldl (+) 0 -- 去掉xs
maxNum x = foldr max 0 x
maxNum' = foldr max 0 -- 去掉x后
定义一些高阶函数
- map
map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (a:as) = (f a) : (map f as)
2. takeWhile
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p [] = []
takeWhile' p (a:as) = if (p a) then a : (takeWhile' p as) else []
3. filter
filter' :: (a->Bool) -> [a] -> [a]
filter' p [] = []
filter' p (x:xs) = if (p x) then x : (filter' p xs) else []
或
filter' :: (a -> Bool) -> [a] -> [a]
filter' p [] = []
filter' p (x:xs) | p x = x : (filter' p xs)
| otherwise = filter' p xs
4. dropWhile
dropWhile' :: (a -> Bool) -> [a] -> [a]
dropWhile' p [] = []
dropWhile' p (x:xs) | p x = dropWhile' p xs
| otherwise = xs
高阶函数的应用和组合
drop 和 dropWhile
replicate函数
replicate n x:生成含有n个x的序列
($)与(.)的不同
$
这个是函数应用符,它主要被用来降低函数的优先级,即这个函数具有右结合性
我们可知$接受(a -> b) 和 a这两个参数
返回值与其第一个参数(a -> b)的返回值相同,第一个参数也是个函数
例如f $ x
其实就等于f x,则相当于将a输入(a -> b)这个函数中
右结合性的用法:
f a (b c)
f a $ b c
上面两个函数的结果是一样的,先计算了最右侧表达式的值,用$来代替括号
实际例子
(.)
(.)的作用就是组合函数,将两个函数组合成一个新的函数
即将 (b -> c) . (a -> b) 糅合成一个新的函数 (a -> c)
新生成的这个函数,以第二个参数的输入作为输入,以第一个参数的输出作为输出
数学表达如下:
- f(x) = x + 1, g(x) = 2x,则o(x) = f(g(x))
所以有
总结(.)和($)
(.) 是用来做函数组合的,($) 是用来降低函数执行优先级的