Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute min and max of a tuple list in F#

Tags:

f#

In F#, given game: (int*int) list I'd like to compute minx, maxx, miny, maxy the min and max values for each tuple dimension.

This code works but seems a bit clumsy:

let minX (game: (int*int) list) =  game |> List.map (fun (x,y) -> x) |> Seq.min 
let maxX (game: (int*int) list) =  game |> List.map (fun (x,y) -> x) |> Seq.max 
let minY (game: (int*int) list) =  game |> List.map (fun (x,y) -> y) |> Seq.min 
let maxY (game: (int*int) list) =  game |> List.map (fun (x,y) -> y) |> Seq.max 

Any hint for improvement?

like image 708
sthiers Avatar asked Jan 30 '26 08:01

sthiers


2 Answers

let minX game = List.minBy fst game |> fst
let maxX game = List.maxBy fst game |> fst
let minY game = List.minBy snd game |> snd
let maxY game = List.maxBy snd game |> snd
like image 168
pad Avatar answered Feb 02 '26 01:02

pad


Like John's, but easier to read:

let game = [(1,4);(2,1)]
let minx, miny, maxx, maxy =
    let folder (mx,my,Mx,My) (ax,ay) = min mx ax, min my ay, max Mx ax, max My ay
    ((Int32.MaxValue, Int32.MaxValue, Int32.MinValue, Int32.MinValue), game) ||> List.fold folder
like image 22
Robert Jeppesen Avatar answered Feb 02 '26 03:02

Robert Jeppesen