函數的定義如下:We will often use the term result for the output, and the terms
arguments or parameters for the inputs.

高階函數是至少滿足下列一個條件的函數
以下用Haskell為例子,說明High-Order function的應用。
-------------------
利用list comprehension表達
map :: (a -> b) -> [a] -> [b]
map f xs = [ f x | x <- xs ]
filter :: (a -> Bool) -> [a] -> [a]
filter p xs = [ x | x <- xs , p x ]
其中 f ,p皆為function,map、filter本身皆為function,而傳入的parameter(f、p)也為function。傳入的function的定義,必須和map、filter 中function定義符合。
--------------------
利用recursive表達
map :: (a -> b) -> [a] -> [b]
map :: f [] =[]
map f (x:xs) = f x : map f xs
filter :: (a -> Bool) -> [a] -> [a]
filter :: p [] =[]
filter p (x:xs)
| p x = x: filter p xs
| otherwise = filter p xs
f [] =v (v 為initial value)
f(x:xs) = x @ f xs (@為operation)
!!(NOTE)利用這種recursive,可定義出加總、乘積、 and/or,但可用更高階的角度來看(high order function),定義出foldr
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f v [] =v
foldr f v (x:xs) = f x (foldr f v xs)
---------------------------------------
例1.利用filter求出list中所有偶數的值
f ::Int -> Bool
f n | n>=5 =True
| otherwise =False
filter f [1,2,3,4,5,6,7,8] =>[5,6,7,8]
傳入filter的function必須return Bool
---------------------------------------
例二.利用map求出二個向量的外積 如[1,3,5] [2,4,6] =>[2,12,30]
myproduct :: Int -> Int -> Int
(因為map2的function定義為接收2個parameter,回傳一個Int)
myproduct x y = x * y
map2 :: (Int -> Int -> Int) -> [Int] -> [Int] -> [Int]
map2 f [][] = []
map2 f (x:xs) (y:ys)= f x y : map2 f xs ys
map2 myproduct [1,3,5] [2,4,6] =>[2,12,30]
---------------------------------------
例三.利用recursive定義出sum、product、AND/OR,再用foldr改寫
mysum [] = 0
mysum (x:xs) = x + sum xs
=>mysum[1,2,3,4] =>10
myproduct [] = 1
myproduct (x:xs) = x * myproduct xs
=>myproduct[1,2,3,4] =>24
myAND [] =True
myAND (x:xs) = x && my AND xs
=>myAND[Tue,True] =>True
myOR [] =False
myOR (x:xs) = x || myOR xs
=>myOR[True,False] =>True
利用foldr改寫如下:
- foldr (+) 0 [1,2,3,4] =>10
- foldr (*) 1 [1,2,3,4] =>24
- foldr(&&)True [True,True] =>True
- foldr(||)False[True,False] =>True