Skip to content

Instantly share code, notes, and snippets.

@23Skidoo
Created January 23, 2012 16:15
Show Gist options
  • Save 23Skidoo/1664038 to your computer and use it in GitHub Desktop.
Save 23Skidoo/1664038 to your computer and use it in GitHub Desktop.
Ocaml exercise: remove duplicates from a list
let remove_elt e l =
let rec go l acc = match l with
| [] -> List.rev acc
| x::xs when e = x -> go xs acc
| x::xs -> go xs (x::acc)
in go l []
let remove_duplicates l =
let rec go l acc = match l with
| [] -> List.rev acc
| x :: xs -> go (remove_elt x xs) (x::acc)
in go l []
let sort_and_remove_duplicates l =
let sl = List.sort compare l in
let rec go l acc = match l with
| [] -> List.rev acc
| [x] -> List.rev (x::acc)
| (x1::x2::xs) ->
if x1 = x2
then go (x2::xs) acc
else go (x2::xs) (x1::acc)
in go sl []
let remove_duplicates_using_a_hashtable l =
let open List in
let tbl = Hashtbl.create (length l) in
let f l e =
try
let _ = Hashtbl.find tbl e in l
with
| Not_found ->
Hashtbl.add tbl e ();
e::l
in
List.rev (List.fold_left f [] l)
@nikhilNathwani
Copy link

How about this?

let rec remove_dups lst= match lst with
| [] -> []
| h::t -> h::(remove_dups (List.filter (fun x -> x<>h) t))

Copy link

ghost commented Nov 10, 2016

nikhil, your match | [] -> [] will make the function ALWAYS return []

@flupe
Copy link

flupe commented Nov 14, 2016

nikhil, your match | [] -> [] will make the function ALWAYS return []

No it won't ?
This would be the case if they wrote | _ -> [] which they did not.

@JoneAJ-prog
Copy link

here is the code that can delete the same elements of a single list in ML language
Good Luck**

fun Reverse(nil) = nil
| Reverse([a]) = [a]
| Reverse(a :: y) =
let
val(M) = Reverese(y);
in
(M :: a)
end;

fun ReSet([a]) = [a]
| ReSet(a :: y) =
let
val(M) = Reset(y);
in
if(Search(a , M)) then (a :: M);
end;

fun Search(a , nil) = true
| Search(a , M) = if(a == hd(M)) then false;
else Search(a , tl(M));

fun DeleteSame(nil) = nil
| DeleteSame([a]) = [a]
| DeleteSame(a :: y) = Reset o Reverse(a :: y);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment