Лекция 7. Функции высших порядков

реклама
Ëåêöèÿ 7. Ôóíêöèè âûñøèõ ïîðÿäêîâ
Ïåðåæîãèí À.Ñ.
8 îêòÿáðÿ 2012 ã.
1/8
Ôóíêöèè âûñøèõ ïîðÿäêîâ
Ôóíêöèÿ íàçûâàåòñÿ ôóíêöèåé âûñøåãî ïîðÿäêà, åñëè â êà÷åñòâå
àðãóìåíòà ïðèíèìàåò ôóíêöèþ èëè âîçâðàùàåò ôóíêöèþ êàê
ðåçóëüòàò.
twice :: (a -> a) -> a -> a
twice f x = f ( f x )
2/8
Ôóíêöèÿ map
Áèáëèîòå÷íàÿ ôóíêöèÿ âûñøåãî ïîðÿäêà map ïðèìåíÿåòñÿ ê
êàæäîìó ýëåìåíòó ñïèñêà
map :: (a -> b) -> [a] -> [b]
Ïðèìåð.
> map (+1) [1,3,5,7]
[2,4,6,8]
Ôóíêöèÿ map ìîæåò áûòü îïðåäåëåíà ñ ïîìîùüþ ãåíåðàòîðà ñïèñêà
map f xs = [f x | x <- xs]
èëè ñ ïîìîùüþ ðåêóðñèè
map f [] = []
map f xs = f x : map f xs
3/8
Ôóíêöèÿ lter
Ôóíêöèÿ ôèëüòðàöèè âûñîêîãî ïîðÿäêà âûáèðàåò çíà÷åíèÿ èç
ñïèñêà, êîòîðûå óäîâëåòâîðÿþò óñëîâèþ.
filter :: (a -> Bool) -> [a] -> [a]
Íàïðèìåð,
> filter even [1..10]
[2,4,6,8,10]
Îáúÿâëåíèå ôóíêöèè lter ñ ïîìîùüþ ãåíåðàòîðà ñïèñêà
filter p xs = [x | x <- xs, p x]
èëè ñ ïîìîùüþ ðåêóðñèè
filter p [] = []
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
4/8
Ôóíêöèÿ foldr
Ôóíêöèè îáðàáîòêè ñïèñêîâ ìîãóò áûòü ïðåäñòàâëåíû ñëåäóþùåé
ïðîñòîé ñõåìîé
f [] = v
f (x:xs) = x (+) f xs
Ïðèìåðû.
sum [] = v
sum (x:xs) = x + sum xs
product [] = v
product (x:xs) = x * product xs
and [] = True
and (x:xs) = x && and xs
Äëÿ òîãî, ÷òîáû îáúåäèíèòü âñå ïðèâåäåííûå ïðèìåðû, ñóùåñòâóåò
ôóíêöèÿ âûñîêîãî ïîðÿäêà foldr.
sum
product
or
and
=
=
=
=
foldr
foldr
foldr
foldr
(+) 0
(*) 1
(||) False
(&&) True
5/8
Ôóíêöèÿ foldr
Ñàìà ôóíêöèÿ foldr îïðåäåëÿåòñÿ ñ ïîìîùüþ ðåêóðñèè:
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f v [] = v
foldr f v (x:xs) = f x (foldr f v xs)
Ïðèìåð. length
length = foldr (\_ n -> 1+n) 0
Òî åñòü f (λ _ n -> 1+n), v = 0.
Ïðèìåð. reverse
reverse = foldr (\_ x xs -> xs ++ [x]) []
Ñ ïîìîùüþ ôóíêöèè foldr ìíîãèå ôóíêöèè âûãëÿäÿò áîëåå
êîìïàêòíî è óäîáíî äëÿ äàëüíåéøåãî àíàëèçà.
6/8
Äðóãèå áèáëèîòå÷íûå ôóíêöèè
Âû÷èñëåíèå êîìïîçèöèè äâóõ ôóíêöèé âûïîëíÿåòñÿ ñ ïîìîùüþ (.)
(.) :: (b->c) -> (a->b) -> (a->c)
f . g = \x -> f (g x)
Ïðèìåð.
odd :: Int -> Bool
odd = not . even
Ïðèìåð. all îïðåäåëÿåò óäîâëåòâîðÿþò ëè âñå ýëåìåíòû ñïèñêà
óñëîâèþ
all :: (a -> Bool) -> [a] -> Bool
all p xs = and [p x | x <- xs]
> all even [2,4,6]
True
7/8
Êîíòðîëüíûå çàäàíèÿ
Ïåðåîïðåäåëèòü ôóíêöèþ map f è lter p ÷åðåç ôóíêöèþ foldr.
8/8
Скачать