Jim Lewis
Jim Lewis

Reputation: 359

How to simplify this F# code

Isn't there a cleaner way to do this?

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

Upvotes: 2

Views: 127

Answers (1)

Mark Pattison
Mark Pattison

Reputation: 3039

The main improvement is to use pattern matching to extract data from tuples.

I would go with something along the following lines (shown as a function called myFunc which I've called with example data to check my understanding of your intention):

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)

You could shorten myFunc even more be piping the definition of triplets into List.maxBy, but at some cost of readability, like this:

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

phoog's suggestion would remove the matching:

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

Upvotes: 1

Related Questions