Created
April 20, 2017 18:32
-
-
Save enil/5ff73b9fc1b1e92f3663a953f867394f to your computer and use it in GitHub Desktop.
Implementation of basic set functionality with an ordered list (like ordset).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(myordset). | |
-export([new/0, add_element/2, del_element/2, union/2, intersect/2, is_subset/2]). | |
new() -> []. | |
add_element(E, []) -> [E]; | |
add_element(E, [E|_] = L) -> L; | |
add_element(E, [H|T]) when E < H -> [E,H|T]; | |
add_element(E, [H|T]) when E > H -> [H|add_element(E, T)]. | |
del_element(_, []) -> []; | |
del_element(E, [E|T]) -> T; | |
del_element(E, [H|_] = L) when E < H -> L; | |
del_element(E, [H|T]) when E > H -> [H|del_element(E, T)]. | |
union([], []) -> []; | |
union(L1, []) -> L1; | |
union([], L2) -> L2; | |
union([H|T1], [H|T2]) -> [H|union(T1, T2)]; | |
union([H1|T1], [H2|_] = L2) when H1 < H2 -> [H1|union(T1, L2)]; | |
union([H1|_] = L1, [H2|T2]) when H2 < H1 -> [H2|union(L1, T2)]. | |
intersect([], []) -> []; | |
intersect([], _) -> []; | |
intersect(_, []) -> []; | |
intersect([H|T1], [H|T2]) -> [H|intersect(T1, T2)]; | |
intersect([H1|T1], [H2|_] = L2) when H1 < H2 -> intersect(T1, L2); | |
intersect([H1|_] = L1, [H2|T2]) when H2 < H1 -> intersect(L1, T2). | |
is_subset(L, L) -> true; | |
is_subset(_, []) -> false; | |
is_subset([], _) -> true; | |
is_subset([H|T1], [H|T2]) -> is_subset(T1, T2); | |
is_subset([H1|_], [H2|_]) when H1 < H2 -> false; | |
is_subset([H1|_] = L1, [H2|T2]) when H2 < H1 -> is_subset(L1, T2). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment