Skip to content

Instantly share code, notes, and snippets.

@joom
Created April 7, 2014 18:15
Show Gist options
  • Save joom/10026455 to your computer and use it in GitHub Desktop.
Save joom/10026455 to your computer and use it in GitHub Desktop.
List equality checker (regardless of element order)
(* Checks if the two given int lists are the same, regardless of their order *)
(*val permEqual = fn : int list * int list -> bool
- permEqual([1,2,3,4,5], [1,2,3,4,5]);
val it = true : bool
- permEqual([1,5,4,2,3], [1,2,3,4,5]);
val it = true : bool
- permEqual([1,2,3,4],[5,3,6,2]);
val it = false : bool
- permEqual([], []);
val it = true : bool
- permEqual([1],[2]);
val it = false : bool*)
fun permEqual(f : int list, s : int list) : bool =
let
(* building an empty Map *)
val dict = IntListMap.empty
fun aux (f, s, dict) =
case (f, s) of
(* checking if all the keys in the map are 0 *)
([], []) => List.all (fn x => x = 0) (IntListMap.listItems dict)
(* subtract one from the key if exists,
assign -1 if not *)
| ([], y::ys) => let
val prev = case IntListMap.find(dict, y) of
NONE => 0
| SOME a => a
val dict = IntListMap.insert(dict, y, prev - 1)
in
aux([], ys, dict)
end
(* add one to the key if exists, assign 1 if not *)
| (x::xs, _) => let
val prev = case IntListMap.find(dict, x) of
NONE => 0
| SOME a => a
val dict = IntListMap.insert(dict, x, prev + 1)
in
aux(xs, s, dict)
end
in
aux(f, s, dict)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment