From the question linked here, I found this implementation of Union in Scala:
def union(a: Set, b: Set): Set = i => a(i) || b(i)
And Set is
Let say we have object called SoSet
given by
object SoSet {
type Set = Int => Boolean
val a : Set = ???
val b : Set = ???
def isItem(item : Int) = a(item) || b(item)
}
The signature of isItem
is given by Int => Boolean
which is a Set
. So far so good.
But now we just want to return the function isItem
(i.e. a Set
).
So lets define union
function for this (There are no parameters right now. We will add it later).
object SoSet {
//..
def union : Set = isItem // returns the function isItem
}
Now lets refactor the isItem
into a anonymous function.
object SoSet {
//..
def union : Set = {
(item : Int) => a(item) || b(item)
}
}
Lets move Set a and b
from object SoSet
to parameters of def union
. Refactor item
to i
.
object SoSet {
type Set = Int => Boolean
def union(a : Set, b : Set) : Set = (i : Int) => a(i) || b(i)
}
UPDATE
val s1 = Set(1, 2, 3)
val s2 = Set(2, 3, 4)
val s3 = union(s1, s2) // returns the function.. Int => Boolean =
s3(2) // invokes the function & checks if 2 is present in the union