F#Seq差异 [英] F# Seq diff

查看:66
本文介绍了F#Seq差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个序列,如何获得属于这两个序列的所有元素或其中一个元素唯一的所有元素?

示例:

let a = [1..10]
let b = [3; 5; 7]

我该如何计算3 5和7(所有元素在列表中都是 )和1、2、4、6、8、9、10(所有元素不是)共同)

谢谢

解决方案

您要做的只是差异(或相对补数).

F#具有Set模块可以在此处帮助我们.这应该可以完成工作:

let a = [1 .. 10]
let b = [3; 5; 7]

let intersection = Set.intersect (Set.ofList a) (Set.ofList b)
let difference = (Set.ofList a) - (Set.ofList b)

您当然可以根据需要使用Set.toList将结果转换回列表.

正如Mehrdad指出的那样,也可以使用LINQ(甚至BCL中的HashSet类)完成此操作,但是这里的方法似乎最符合F#语言的精神(从语法上讲,当然是最好的,可能也是最高效的.)

given two sequences, how to get all the elements belonging to both the sequences or all the elements unique to one of them?

Example:

let a = [1..10]
let b = [3; 5; 7]

How do I compute 3 5 and 7 (all the elements common to both the list) and 1, 2, 4, 6, 8, 9, 10 (all the elements not in common)

Thanks

解决方案

What you want to do is no more than the simple set operations of intersection and difference (or relative complement).

F# has the Set module to help us out here. This should do the job:

let a = [1 .. 10]
let b = [3; 5; 7]

let intersection = Set.intersect (Set.ofList a) (Set.ofList b)
let difference = (Set.ofList a) - (Set.ofList b)

You can then of course convert back the results into lists using Set.toList, if you wish.

As Mehrdad points out, this can be done alternatively using LINQ (or even the HashSet class in the BCL), but the approach here would seem to be most in the spirit of the F# language (certainly the nicest syntactically, and probably the most efficient too).

这篇关于F#Seq差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆