如何简化这个F#代码

时间:2015-03-01 12:42:00

标签: f# tuples simplify

不是有更清洁的方法吗?

let Triplets = List.zip3 A B C
let T1 (x, _, _) = x
let T2 (_, x, _) = x
let T3 (_, _, x) = x
let Best = List.maxBy T3 Triplets
T1 Best,T2 Best // return to C# code

1 个答案:

答案 0 :(得分:1)

主要的改进是使用模式匹配从元组中提取数据。

我会选择以下几行(显示为一个名为myFunc的函数,我用示例数据调用它来检查我对你的意图的理解):

let A = [1; 2; 3]
let B = [4; 5; 6]
let C = [6; 7; 6]

let myFunc A B C =
    let triplets = List.zip3 A B C
    match List.maxBy (fun (_, _, x) -> x) triplets with
    | (a, b, _) -> (a, b)

let result = myFunc A B C //returns (2, 5)

您可以缩短myFunc,将triplets的定义更多地引入List.maxBy,但这样做会带来一些可读性:

let myFunc A B C =
    match List.zip3 A B C |> List.maxBy (fun (_, _, x) -> x) with
    | (a, b, _) -> (a, b)

phoog的建议将删除匹配:

let myFunc A B C =
    let (a, b, _) = List.zip3 A B C |> List.maxBy (fun (_, _, x) -> x)
    (a, b)