Created
January 23, 2012 16:15
-
-
Save 23Skidoo/1664038 to your computer and use it in GitHub Desktop.
Ocaml exercise: remove duplicates from a list
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
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) |
nikhil, your match | [] -> [] will make the function ALWAYS return []
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.
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
How about this?
let rec remove_dups lst= match lst with
| [] -> []
| h::t -> h::(remove_dups (List.filter (fun x -> x<>h) t))