Check if an element is within a sequence

2020-03-09 05:24发布

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)?

标签: f#
5条回答
贼婆χ
2楼-- · 2020-03-09 05:43

Seq.exists again, but with slightly different syntax -

let testseq = seq [ 1; 2; 3; 4 ]
let testn = 2
testseq |> Seq.exists (fun x -> x = testn)

See MSDN F#: Seq.exists function: https://msdn.microsoft.com/en-us/library/ee353562.aspx

Lots of other good ones there too!

查看更多
不美不萌又怎样
3楼-- · 2020-03-09 05:52

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; ...]

Danny

查看更多
Emotional °昔
4楼-- · 2020-03-09 06:04

Little bit simpler:

let contains x = Seq.exists ((=) x)
查看更多
该账号已被封号
5楼-- · 2020-03-09 06:04

Seq.exists

let testseq = seq [ 1; 2; 3; 4 ]
let equalsTwo n = (n = 2)
let containsTwo = Seq.exists equalsTwo testseq
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-03-09 06:06

(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
        }
查看更多
登录 后发表回答