what is map and filter
They belong to high-order functions(是高階函數(shù)名人堂的成員).
對(duì)于map函數(shù)來(lái)說(shuō),輸入是列表洋措,輸出也是列表蜘渣。使用函數(shù)f對(duì)輸入列表中的每個(gè)元素進(jìn)行處理淌铐,從而得到新的列表。
fun map(f, xs) =
case xs of
[] => []
| x::xs' => (f x) :: map(f, xs')
val x1 = map(fn x=>x+1, [2, 4, 5, 7])
對(duì)于filter函數(shù)來(lái)說(shuō)蔫缸,輸入是列表腿准,輸出也是列表。使用函數(shù)f對(duì)輸入列表中的每個(gè)元素進(jìn)行處理拾碌,如果得到結(jié)果為true吐葱,則保留其元素,否則不保留校翔,從而得到新的列表弟跑。
fun filter(f, xs) =
case xs of
[] => []
| x::xs' => if (f x)
then x::filter(f, xs')
else filter(f, xs')