refactor list functions

This commit is contained in:
Gregory 2020-06-05 01:43:53 +03:00
parent bb7fd94dcd
commit ecb7e60551
3 changed files with 22 additions and 14 deletions

View file

@ -31,7 +31,7 @@ val remove_card: remove_card = fn (cards, to_remove, exp) =>
then (found, card :: acc) then (found, card :: acc)
else (true orelse found, acc) else (true orelse found, acc)
in in
case fold filter (false, []) cards of case foldl filter (false, []) cards of
(true, filtered) => filtered (true, filtered) => filtered
| (false, _) => raise exp | (false, _) => raise exp
end end
@ -47,10 +47,11 @@ val rec all_same_color: all_same_color = fn cards =>
type sum_cards = card list -> int type sum_cards = card list -> int
val sum_cards: sum_cards = fn cards => val sum_cards: sum_cards = fn cards =>
cards |> fold (fn card => fn sum => card_value card + sum) 0 cards |> foldl (fn card => fn sum => card_value card + sum) 0
fun sum a b = a + b
(* even shorter via partial application :) *) (* even shorter via partial application :) *)
val sum_cards: sum_cards = fold (fn card => fn sum => card_value card + sum) 0 val sum_cards: sum_cards = foldl (card_value >> sum) 0
type score = card list * int -> int type score = card list * int -> int
val score: score = fn (cards, goal) => val score: score = fn (cards, goal) =>
@ -83,5 +84,5 @@ val officiate: officiate = fn (deck, moves, goal) =>
fun round hand = score (hand, goal) fun round hand = score (hand, goal)
in in
moves |> fold play (deck, []) |> #2 |> round moves |> foldl play (deck, []) |> #2 |> round
end end

View file

@ -212,4 +212,11 @@ val 0 =
|> (fn _ => expected) |> (fn _ => expected)
end end
fun by2 a = a * 2
val () =
assert
$ map by2 [1, 2, 3] = [2, 4, 6]
$ "map test"
val () = complete () val () = complete ()

View file

@ -2,23 +2,22 @@ use "operators.sml";
fun cons head tail = head :: tail fun cons head tail = head :: tail
fun fold f acc lst = fun foldl f acc lst =
case lst of case lst of
[] => acc [] => acc
| head :: tail => fold f (f head acc) tail | head :: tail => foldl f (f head acc) tail
fun reverse lst = fun reverse lst = foldl cons [] lst
let
fun f elm acc = elm :: acc fun foldr f acc = foldl f acc >> reverse
in
fold f [] lst fun map f = foldr (f >> cons) []
end
fun filter predicate lst = fun filter predicate lst =
let let
fun f elm acc = if predicate elm then elm :: acc else acc fun f elm acc = if predicate elm then elm :: acc else acc
in in
lst |> fold f [] |> reverse foldr f [] lst
end end
fun empty lst = lst = [] fun empty lst = lst = []
@ -27,4 +26,5 @@ fun empty lst = lst = []
fun exists elem lst = fun exists elem lst =
lst lst
|> filter (fn needle => elem = needle) |> filter (fn needle => elem = needle)
|> not o empty |> empty
|> not