From ddba860d353d86c3daa8c3bf7054e9f73c43eac4 Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Wed, 14 Aug 2019 23:22:54 +0100 Subject: list:sort requires comparison function --- gen/src/gleam@list.erl | 18 +++++++++--------- gen/test/gleam@list_test.erl | 9 ++++----- 2 files changed, 13 insertions(+), 14 deletions(-) (limited to 'gen') diff --git a/gen/src/gleam@list.erl b/gen/src/gleam@list.erl index 548e983..411a6c8 100644 --- a/gen/src/gleam@list.erl +++ b/gen/src/gleam@list.erl @@ -1,7 +1,7 @@ -module(gleam@list). -compile(no_auto_import). --export([length/1, reverse/1, is_empty/1, contains/2, head/1, tail/1, filter/2, map/2, index_map/2, traverse/2, drop/2, take/2, new/0, append/2, flatten/1, fold/3, fold_right/3, find/2, all/2, any/2, zip/2, strict_zip/2, intersperse/2, at/2, unique/1, sort/1, range/2, repeat/2, split/2, split_while/2]). +-export([length/1, reverse/1, is_empty/1, contains/2, head/1, tail/1, filter/2, map/2, index_map/2, traverse/2, drop/2, take/2, new/0, append/2, flatten/1, fold/3, fold_right/3, find/2, all/2, any/2, zip/2, strict_zip/2, intersperse/2, at/2, unique/1, sort/2, range/2, repeat/2, split/2, split_while/2]). length(A) -> erlang:length(A). @@ -277,7 +277,7 @@ unique(List) -> [X | unique(filter(Rest, fun(Y) -> Y /= X end))] end. -merge_sort(A, B) -> +merge_sort(A, B, Compare) -> case {A, B} of {[], _} -> B; @@ -286,16 +286,16 @@ merge_sort(A, B) -> A; {[Ax | Ar], [Bx | Br]} -> - case Ax < Bx of - true -> - [Ax | merge_sort(Ar, B)]; + case Compare(Ax, Bx) of + lt -> + [Ax | merge_sort(Ar, B, Compare)]; - false -> - [Bx | merge_sort(A, Br)] + _ -> + [Bx | merge_sort(A, Br, Compare)] end end. -sort(List) -> +sort(List, Compare) -> ListLength = length(List), case ListLength < 2 of true -> @@ -305,7 +305,7 @@ sort(List) -> SplitLength = ListLength div 2, AList = take(List, SplitLength), BList = drop(List, SplitLength), - merge_sort(sort(AList), sort(BList)) + merge_sort(sort(AList, Compare), sort(BList, Compare), Compare) end. range(Start, Stop) -> diff --git a/gen/test/gleam@list_test.erl b/gen/test/gleam@list_test.erl index 942bee8..1037884 100644 --- a/gen/test/gleam@list_test.erl +++ b/gen/test/gleam@list_test.erl @@ -179,12 +179,11 @@ unique_test() -> gleam@expect:equal(gleam@list:unique([]), []). sort_test() -> - gleam@expect:equal(gleam@list:sort([4, 3, 6, 5, 4]), [3, 4, 4, 5, 6]), - gleam@expect:equal(gleam@list:sort([]), []), gleam@expect:equal( - gleam@list:sort([{1, 2}, {4, 5}, {3, 2}]), - [{1, 2}, {3, 2}, {4, 5}] - ). + gleam@list:sort([4, 3, 6, 5, 4], fun gleam@int:compare/2), + [3, 4, 4, 5, 6] + ), + gleam@expect:equal(gleam@list:sort([], fun gleam@int:compare/2), []). index_map_test() -> gleam@expect:equal( -- cgit v1.2.3