简体   繁体   中英

How can I make this Join in F#?

I have a lambda join in C# which looks like this:

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.

I want to make the exact same lambda join in F#, and try:

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. Expected '->' or other token.

The error is the comma after the first parameter arrY.

Can you tell me how I can get it to work (as a lambda expression)?

this will work for me in F#-interactive (and is the direct translation from your C# code):

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;;
val it : Collections.Generic.IEnumerable<int> = seq [3]

remarks

if you like you can write

let res = arrX.Join(arrY, (fun x -> x), (fun x -> x), fun x _ -> x)

as @RCH proposed too

Note that there are at least two ways to do this using the F# core lib.

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

:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM