我怎样才能加入F#?

时间:2015-05-19 17:32:20

标签: .net linq lambda 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表达式)吗?

3 个答案:

答案 0 :(得分:3)

这对我来说在F#-interactive中起作用(并且是你的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提议的那样

答案 1 :(得分:1)

请注意,使用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
    }

答案 2 :(得分:0)

我可以大胆地提出以下建议:

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'版本......

: - )