From ecb7e60551c8024fb4c523400261aaf3c0273bd2 Mon Sep 17 00:00:00 2001 From: Gregory Date: Fri, 5 Jun 2020 01:43:53 +0300 Subject: [PATCH] refactor list functions --- sml/week3/card.sml | 9 +++++---- sml/week3/card_tests.sml | 7 +++++++ sml/week3/list.sml | 20 ++++++++++---------- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/sml/week3/card.sml b/sml/week3/card.sml index 9983c8b..22bed19 100644 --- a/sml/week3/card.sml +++ b/sml/week3/card.sml @@ -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 \ No newline at end of file diff --git a/sml/week3/card_tests.sml b/sml/week3/card_tests.sml index 0b24359..42be3a8 100644 --- a/sml/week3/card_tests.sml +++ b/sml/week3/card_tests.sml @@ -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 () \ No newline at end of file diff --git a/sml/week3/list.sml b/sml/week3/list.sml index 6d24a75..f5c4804 100644 --- a/sml/week3/list.sml +++ b/sml/week3/list.sml @@ -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 \ No newline at end of file + |> empty + |> not \ No newline at end of file