Reputation: 2614
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)?
Upvotes: 1
Views: 143
Reputation: 1188
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...
:-)
Upvotes: 0
Reputation: 47904
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
}
Upvotes: 1
Reputation: 52280
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]
if you like you can write
let res = arrX.Join(arrY, (fun x -> x), (fun x -> x), fun x _ -> x)
as @RCH proposed too
Upvotes: 3