[英]How can I make this Join in F#?
我在C#中有一个lambda联接,如下所示:
int[] arrX = { 1, 2, 3 };
int[] arrY = { 3, 4, 5 };
var res = arrX.Join(arrY, x => x, y => y, (x, y) => x);
执行后,res包含两个数组都通用的3。
我想在F#中使用完全相同的lambda连接,然后尝试:
let arrX = [| 1; 2; 3 |]
let arrY = [| 3; 4; 5 |]
let res = arrX.Join(fun arrY, fun x -> x, fun y -> y, fun (x, y) -> x)
但是编译器说:
Lambda表达式中出现意外的符号','。 预期的'->'或其他标记。
错误是第一个参数arrY之后的逗号。
您能告诉我如何使其工作(作为lambda表达式)吗?
这将在F#交互式环境中为我工作(这是您C#代码的直接翻译):
open System
open System.Linq
let arrX = [| 1; 2; 3 |]
let arrY = [| 3; 4; 5 |]
let res = arrX.Join(arrY, Func<_,_>(id), Func<_,_>(id), (fun x _ -> x))
执行res
将如下所示:
> res;;
val it : Collections.Generic.IEnumerable<int> = seq [3]
如果你愿意,你可以写
let res = arrX.Join(arrY, (fun x -> x), (fun x -> x), fun x _ -> x)
正如@RCH也建议
请注意,至少有两种方法可以使用F#核心库执行此操作。
let arrX = [| 1; 2; 3 |]
let arrY = [| 3; 4; 5 |]
//method 1 (does not preserve order)
let res1 = Set.intersect (set arrX) (set arrY)
//method 2
let res2 =
query {
for x in arrX do
join y in arrY on (x = y)
select x
}
我可以大胆地提出以下建议:
open System
open System.Linq
let arrX = [| 1; 2; 3 |]
let arrY = [| 3; 4; 5 |]
let res = Set.intersect (Set.ofArray arrX) (Set.ofArray arrY) |> Set.toArray
或者如果要使用某种“混淆风格”:
let res' = arrX |> Set.ofArray |> Set.intersect <| (Set.ofArray <| arrY) |> Set.toArray
我猜不建议使用res版本。
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.