簡體   English   中英

如何在F#中加入此Join?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM