Reputation: 1179
I am not even sure if this is about closures, but I cannot reason about e
in the following code.
type Set = Int => Boolean
/* characteristic function of Set */
def contains(s: Set, elem: Int): Boolean = s(elem)
/* definition of a singleton set, returning a set of only one given element */
def singletonSet(elem: Int): Set = e => e == elem
In the above code, where does the e
come from? How can I reason about that?
Upvotes: 1
Views: 70
Reputation: 149538
This isn't about closure. e
simply represents an element of type Int
as dictated by the declaration of the Set
type, which is an alias for a Function1[Int, Bool]
. Think of e
as a placeholder for future Int
values which you'll pass. This is simply anonymous function syntax.
When you call singletonSet
, you'll have to pass the Int
parameter which e
will reflect:
println(contains(singletonSet(1), 1)) // yields true
println(contains(singletonSet(1), 2)) // yields false
The same would work if you passed an anonymous function directly:
println(contains(e => e == 1, 1))
Upvotes: 2