Take the 2-minute tour ×

how to check if an element is contained within a sequence? I expected some Seq.contains, but i could not find it. Thanks

EDIT: Or, for an easier task, how to make the diff between two sequences? Like, getting all the elements within a list that doesn not belong to another (or that do)?

share|improve this question
For your second question, see here: stackoverflow.com/questions/1158114/f-seq-diff –  Benjol Jul 23 '09 at 6:25
add comment

4 Answers

Little bit simpler:

let contains x = Seq.exists ((=) x)
share|improve this answer
add comment


let testseq = seq [ 1; 2; 3; 4 ]
let equalsTwo n = (n = 2)
let containsTwo = Seq.exists equalsTwo testseq
share|improve this answer
add comment

Set is your friend here:

let a = set [0;1;2;3]
let b = set [2;3;4;5]
let c = a - b
let d = b - a
let e = Set.intersect a b
let f = a + b
val c : Set<int> = seq [0; 1]
val d : Set<int> = seq [4; 5]
val e : Set<int> = seq [2; 3]
val f : Set<int> = seq [0; 1; 2; 3; ...]


share|improve this answer
add comment

(Another question, another answer.)

This works, but I don't think that it's the most idomatic way to do it - (you'll need to wait until the US wakes up to find out):

let s1 = seq [ 1; 2; 3; 4 ]
let s2 = seq [ 3; 4; 5; 6 ]

seq {
    for a in s1 do
        if not (Seq.exists (fun n -> n = a) s2) then
            yield a
share|improve this answer
What you have is an O(nm) algorithm, where n is the length of the first list and m is the length of the second. When n and m are approximately equal to one another, you might as well consider this an O(n^2) algorithm. I think there are much more efficient ways to compute the intersection of a set than this. –  Juliet Jul 21 '09 at 13:19
add comment

Your Answer


