In the code snippet you show above, any set S
is represented by what is called its characteristic function, i.e., a function that given some integer i
checks whether i
is contained in the set S
or not. Thus you can think of such a characteristic function f
like it was a set, namely
{
i
| all integersi
for whichf i
istrue
}
If you think of any function with type Int => Boolean
as set (which is indicated by the type synonym Set = Int => Boolean
) then you could describe contains
by
Given a set
f
and an integeri
,contains(f, i)
checks whetheri
is an element off
or not.
Some example sets might make the idea more obvious:
Set Characeristic Function
empty set x => false
universal set x => true
set of odd numbers x => x % 2 == 1
set of even numbers x => x % 2 == 0
set of numbeers smaller than 10 x => x < 10
Example: The set {1, 2, 3} can be represented by
val S: Set = (x => 0 <= x && x <= 3)
If you want to know whether some number n
is in this set you could do
contains(S, n)
but of course (as you already observed yourself) you would get the same result by directly doing
S(n)
While this is shorter, the former is maybe easier to read (since the intention is somewhat obvious).