Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Sep 25th, 2009  |  syntax: OCaml  |  size: 0.66 KB  |  views: 156  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. (*
  2. I want to return a list of common elements shared between two lists.
  3. In particular, I want the cartesian product of two lists, such that:
  4.  
  5. let x = [2; 4; 6; 8; 8; 10; 12]
  6. let y = [-7; -8; 2; 2; 3; 4; 4; 8; 8; 8;]
  7.  
  8. join(x, y) = [2; 2; 4; 4; 8; 8; 8; 8; 8; 8]
  9.  
  10. The following code is close to what I want: it returns distinct
  11. elements shared between two lists, such that join(x, y) = [2; 3; 4; 8; 9]
  12.  
  13. -- Juliet
  14. *)
  15.  
  16. let join x y =
  17.     let rec loop = function
  18.         | [], y | y, [] -> y
  19.         | (x::xs as x'), (y::ys as y') ->
  20.             if x = y then y :: loop(xs, ys)
  21.             elif x > y then loop(x', ys)
  22.             else loop(xs, y')
  23.     loop(x, y)