Adding two tuples in F#

Viewed 616

Trying to understand tuples in F#..

Current thought process

let add tuples a b = 
let a = (_,_)
let b= (_,_)
(a+b)

this won't work due to "_" being invalid for this case so then I thought to try

let add tuples a b =
let a = (c,d)
let b = (e,f)
fst a + fst b, snd a + snd b;;

this won't work because c,d,e,&f are not known variables. In java I would traditionally just initialize that variable so it can be used but in F# that seems a bit funky let a= int not even sure if that would work anyways

any help on trying to fix my thought process would be appreciated. Thanks

edit:

expected result

a (1,3) b (2,4) return (3,7)

1 Answers

There are two ways of accessing elements from a tuple and your code seems to be confusing them. First, you can use fst and snd on two-element tuples. You actually have this right, but you need to remove other unnecessary lines - a and b are tuples, so you can write just:

let add a b =
  fst a + fst b, snd a + snd b

The other option is to use pattern matching. To do this, you need to assing a tuple value, i.e. a or b to a pattern that defines new variables like (c, d). Doing the above using pattern matching looks like this:

let add a b =
  let (a1, a2) = a
  let (b1, b2) = b
  a1 + b1, a2 + b2

Patterns can appear in stand-alone let bindings like above, but you can also use them directly in the arguments of a function - so you can shorted this to:

let add (a1, a2) (b1, b2) = 
  a1 + b1, a2 + b2
Related