Skip to content

Instantly share code, notes, and snippets.

@awostenberg
Last active November 10, 2020 00:23
Show Gist options
  • Save awostenberg/797b59cdc5a10b20804066221f097ca1 to your computer and use it in GitHub Desktop.
Save awostenberg/797b59cdc5a10b20804066221f097ca1 to your computer and use it in GitHub Desktop.
list intersection
//a: how would you compute intersection of two lists?
//b: I'd use set intersection, but if literally a list, I'd sort then merge:
let intersection a b =
let rec intersection' a b =
match a,b with
| _,[] -> []
| [],_ -> []
| x::a',y::b' when x=y -> x::intersection' a' b'
| x::a',y::_ when x<y -> intersection' a' b
| x::_,y::b' when x>y -> intersection' a b'
intersection' (List.sort a) (List.sort b)
[
intersection [] [] = []
intersection ['a'] ['a'] = ['a']
intersection ['a'] ['b'] = []
intersection ['a';'b'] ['a';'b'] = ['a';'b']
intersection ['a';'c'] ['c'] = ['c']
intersection ['c'] ['a';'c'] = ['c']
intersection ['b'] [] = []
intersection [] ['b'] = []
intersection ['a';'b';'c'] ['a'] = ['a']
intersection ['a'] ['a';'b';'c'] = ['a']
intersection ['a';'b'] ['b';'a'] = ['a';'b']
intersection ['a'..'d'] ['b'..'g'] = ['b'..'d']
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment