Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library function to find difference between two lists - OCaml

Tags:

ocaml

Is there a library function to find List1 minus elements that appear in List2? I've been googling around and haven't found much.

It doesn't seem too trivial to write it myself. I've written a function to remove a specific element from a list but that's much more simple:

let rec difference l arg = match l with
| [] -> []
| x :: xs -> 
    if (x = arg) then difference xs arg
    else x :: difference xs arg;;
like image 241
Collin Avatar asked Oct 20 '25 12:10

Collin


2 Answers

Will this do?

let diff l1 l2 = List.filter (fun x -> not (List.mem x l2)) l1
like image 51
Jackson Tale Avatar answered Oct 23 '25 09:10

Jackson Tale


What I ended up actually doing was just writing another function which would call the first one I posted

let rec difference l arg = match l with
    | [] -> []
    | x :: xs -> 
        if (x = arg) then difference xs arg
        else x :: difference xs arg;; 

let rec list_diff l1 l2 = match l2 with
    | [] -> l1
    | x :: xs -> list_diff (difference l1 x) xs;;

Although the solution I accepted is much more elegant

like image 36
Collin Avatar answered Oct 23 '25 07:10

Collin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!