Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map every 2 elements to a function/constructor

Tags:

f#

I have an integer array in which I want to send every two elements from it to the constructor of another function.

Something like intArray |> Array.map (fun x, y -> new Point(x, y))

Is this possible? I'm new to F# and functional programming so I'm trying to avoid just looping through every 2 items in the array and adding the point to a list. I hope that's reasonable.

like image 219
Shelby115 Avatar asked May 02 '26 13:05

Shelby115


1 Answers

If using F# 4.0, use Gustavo's approach. For F# 3, you can do:

intArray
    |> Seq.pairwise // get sequence of tuples of element (1,2); (2,3); (3,4); (4,5) etc
    |> Seq.mapi (fun i xy -> i, xy) // combine the index with the tuple
    |> Seq.filter (fun (i,_) -> i % 2 = 0) // Filter for only the even indices to get (1,2); (3,4)
    |> Seq.map (fun xy -> Point xy) // make a point from the tuples
    |> Array.ofSeq // convert back to array
like image 187
TheInnerLight Avatar answered May 04 '26 05:05

TheInnerLight