Identify If The List Is Empty

I am entirely new to F# I have this function that calculates the sum of the two different x and y points like this let vAdd (x1, y1) (x2, y2) : float * float = (x1 + x2, y1 + y2) and then I have another function that takes a list of the points and then uses vAdd to do the calculation. let vSum [(x1, y1); (x2, y2)] = vAdd (x1, y1) (x2, y2)

Now my question would be, how would I check and throw some error if the list given is empty? I tried with if ... then failwith "list is empty" but IsEmpty wasn't working. Another thing that I have looked at was pattern matching, but again, I don't know how it would work with my specific function. F# Check if a list is empty

Any help would be appreciated, and thanks in advance!

1 answer

  • answered 2022-01-25 01:01 Tomas Petricek

    The most elegant approach is to use pattern matching, which lets you check that the list has exactly two elements and extract their values:

    let vSum list = 
      match list with
      | [(x1, y1); (x2, y2)] -> vAdd (x1, y1) (x2, y2)
      | _ -> failwith "The list did not have two elements!"

    You can slightly shorten this by using the function keyword, which is a shortcut for a function taking a variable and pattern matching on it:

    let vSum = function
      | [(x1, y1); (x2, y2)] -> vAdd (x1, y1) (x2, y2)
      | _ -> failwith "The list did not have two elements!"

    That said, if you always want to pass around two things, you should not be using a list, but use a tuple instead. You can have a tuple of tuples - that is fine - but if you know it is exactly two elements, then using a list is breaking the rule "make invalid states unrepresentable".

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum