programming_languages/sml/week3/list.sml

30 lines
573 B
Standard ML
Raw Permalink Normal View History

2020-06-04 03:02:24 +03:00
use "operators.sml";
fun cons head tail = head :: tail
2020-06-05 01:43:53 +03:00
fun foldl f acc lst =
2020-06-04 03:02:24 +03:00
case lst of
[] => acc
2020-06-05 01:43:53 +03:00
| head :: tail => foldl f (f head acc) tail
2020-06-04 03:02:24 +03:00
2020-06-05 01:43:53 +03:00
fun reverse lst = foldl cons [] lst
fun foldr f acc = foldl f acc >> reverse
fun map f = foldr (f >> cons) []
2020-06-04 03:02:24 +03:00
fun filter predicate lst =
let
fun f elm acc = if predicate elm then elm :: acc else acc
in
2020-06-05 01:43:53 +03:00
foldr f [] lst
2020-06-04 03:02:24 +03:00
end
fun empty lst = lst = []
(* not efficient but works *)
fun exists elem lst =
lst
|> filter (fn needle => elem = needle)
2020-06-05 01:43:53 +03:00
|> empty
|> not