refactor list functions
This commit is contained in:
parent
bb7fd94dcd
commit
ecb7e60551
3 changed files with 22 additions and 14 deletions
|
@ -31,7 +31,7 @@ val remove_card: remove_card = fn (cards, to_remove, exp) =>
|
|||
then (found, card :: acc)
|
||||
else (true orelse found, acc)
|
||||
in
|
||||
case fold filter (false, []) cards of
|
||||
case foldl filter (false, []) cards of
|
||||
(true, filtered) => filtered
|
||||
| (false, _) => raise exp
|
||||
end
|
||||
|
@ -47,10 +47,11 @@ val rec all_same_color: all_same_color = fn cards =>
|
|||
|
||||
type sum_cards = card list -> int
|
||||
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 :) *)
|
||||
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
|
||||
val score: score = fn (cards, goal) =>
|
||||
|
@ -83,5 +84,5 @@ val officiate: officiate = fn (deck, moves, goal) =>
|
|||
|
||||
fun round hand = score (hand, goal)
|
||||
in
|
||||
moves |> fold play (deck, []) |> #2 |> round
|
||||
moves |> foldl play (deck, []) |> #2 |> round
|
||||
end
|
|
@ -212,4 +212,11 @@ val 0 =
|
|||
|> (fn _ => expected)
|
||||
end
|
||||
|
||||
fun by2 a = a * 2
|
||||
|
||||
val () =
|
||||
assert
|
||||
$ map by2 [1, 2, 3] = [2, 4, 6]
|
||||
$ "map test"
|
||||
|
||||
val () = complete ()
|
|
@ -2,23 +2,22 @@ use "operators.sml";
|
|||
|
||||
fun cons head tail = head :: tail
|
||||
|
||||
fun fold f acc lst =
|
||||
fun foldl f acc lst =
|
||||
case lst of
|
||||
[] => acc
|
||||
| head :: tail => fold f (f head acc) tail
|
||||
| head :: tail => foldl f (f head acc) tail
|
||||
|
||||
fun reverse lst =
|
||||
let
|
||||
fun f elm acc = elm :: acc
|
||||
in
|
||||
fold f [] lst
|
||||
end
|
||||
fun reverse lst = foldl cons [] lst
|
||||
|
||||
fun foldr f acc = foldl f acc >> reverse
|
||||
|
||||
fun map f = foldr (f >> cons) []
|
||||
|
||||
fun filter predicate lst =
|
||||
let
|
||||
fun f elm acc = if predicate elm then elm :: acc else acc
|
||||
in
|
||||
lst |> fold f [] |> reverse
|
||||
foldr f [] lst
|
||||
end
|
||||
|
||||
fun empty lst = lst = []
|
||||
|
@ -27,4 +26,5 @@ fun empty lst = lst = []
|
|||
fun exists elem lst =
|
||||
lst
|
||||
|> filter (fn needle => elem = needle)
|
||||
|> not o empty
|
||||
|> empty
|
||||
|> not
|
Loading…
Reference in a new issue