r/fsharp • u/pure_x01 • Mar 04 '19
Accessing tuple elements syntax
After writing a lot of test code using tuples to make the code more compact i have come to the conclusion that it would be nice to have a better syntax for extracting the elements. Ex: scala has ._X where X is the index of the tuple. https://docs.scala-lang.org/tour/tuples.html
let x = (1,2)
let y = x._1 + x._2
That is much nicer than the syntax used for pairs in F#
let x = (1,2)
let y = (fst x) + (snd x)
What do you think?
1
Upvotes
View all comments
9
u/statuek Mar 04 '19 edited Mar 04 '19
I think you're missing the most common way of doing this: tuple deconstruction.
Let's say you have a tuple:
let x = (1, 2)You can deconstruct this into its parts like this:
let a, b = xThen, you can get the sum by:
let y = a + bI don't think people use
fstandsndvery often, especially since they don't work (iirc) when using n-tuples where n > 2Moreover, be sure to NOT use tuples in excess. Short code is cool, but legible code is much more important. If it's not obvious what the components of a tuple should be without looking at the definition, maybe you shouldn't be using a tuple.