[英]How can I make this Join in F#?
I have a lambda join in C# which looks like this: 我在C#中有一个lambda联接,如下所示:
int[] arrX = { 1, 2, 3 };
int[] arrY = { 3, 4, 5 };
var res = arrX.Join(arrY, x => x, y => y, (x, y) => x);
After execution res contains 3 which is common for both arrays. 执行后,res包含两个数组都通用的3。
I want to make the exact same lambda join in F#, and try: 我想在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)
But the compiler says: 但是编译器说:
Unexpected symbol ',' in lambda expression. Lambda表达式中出现意外的符号','。 Expected '->' or other token. 预期的'->'或其他标记。
The error is the comma after the first parameter arrY. 错误是第一个参数arrY之后的逗号。
Can you tell me how I can get it to work (as a lambda expression)? 您能告诉我如何使其工作(作为lambda表达式)吗?
this will work for me in F#-interactive (and is the direct translation from your C# code): 这将在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))
after executing res
will look like this: 执行res
将如下所示:
> res;;
val it : Collections.Generic.IEnumerable<int> = seq [3]
if you like you can write 如果你愿意,你可以写
let res = arrX.Join(arrY, (fun x -> x), (fun x -> x), fun x _ -> x)
as @RCH proposed too 正如@RCH也建议
Note that there are at least two ways to do this using the F# core lib. 请注意,至少有两种方法可以使用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
}
May I boldly suggest the following: 我可以大胆地提出以下建议:
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
or if going for some total "obfuscation style": 或者如果要使用某种“混淆风格”:
let res' = arrX |> Set.ofArray |> Set.intersect <| (Set.ofArray <| arrY) |> Set.toArray
I guess the res'-version is not recommended... 我猜不建议使用res版本。
:-) :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.