Finding a subset, but F# will not let me compare two sets of different lengths

StackOverflow https://stackoverflow.com/questions/23587696

  •  19-07-2023
  •  | 
  •  

Question

I'm trying to find if one set is a subset of the other. My code works perfectly if both sets are the same length.

For example,

My code will return true if

x = [a;b;c] y = [a;b;c]

My code will return false if

x = [a;b;c] y = [a;b;d]

However, my code will not even compile if I try

x = ['a';'b';'c'] y = ['a';'b';'c';'d']

It's supposed to return true, but I get the following error message:

Type mismatch. 
Expecting a Set<char * char * char> but given a Set<char * char * char * char> 

The tuples have differing lengths of 3 and 4

My code is below

let mySubList x y =
printfn "%A is a proper subset of %A: %b" x y (Set.isSubset x y)

let x = Set.empty.Add('a','b','c')
let y = Set.empty.Add('a','b','c', 'd')
let z = Set.empty.Add('a','x','a','y','c','e')

let found = mySubList x y
Was it helpful?

Solution

All your sets contain the same number of elements: they all contain exactly one element. However they contain elements of different types, which is why you can't compare. Namely x contains a 3-tuple (char * char * char), y contains a 4-tuple and z contains a 5 tuple.

The important thing to note here is that Add('a', 'b', 'c') doesn't call Add with multiple arguments - it calls it with one argument, which is a tuple. This will add a single tuple element to the set. To add multiple elements, use Add multiple times or just use the set on a list (i.e. set ['a'; 'b'; 'c']) instead of Add to avoid multiple function calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top