Reputation: 192
I've been asked to create a singletonSet function which creates a singleton set from one integer value: The code I used:
def singletonSet(elem: Int): Set = {
def isInSet (givenElement: Int) =
if (elem == givenElement) true
else false
isInSet
}
checking online somebody did:
def singletonSet(elem: Int): Set = {
x => List(elem).contains(x)
}
does that mean he/she put the element in a list and called the .contains() function on it? and I don't get what x does here? I tried this code. It runs with no error. I just don't get it. Thank you.
Upvotes: 1
Views: 1847
Reputation: 462
As I understand
type Set = Int => Boolean
So x is just an Int that the returned function applies.
does that mean he/she put the element in a list and called the .contains() function on it?
Yes it looks so and we can simplify it:
def singletonSet(elem: Int): Int => Boolean = {
x:Int => elem == x:Boolean
}
Let's remove types
def singletonSet(elem: Int): Int => Boolean = {
x => elem == x
}
and replace x with placeholder _
def singletonSet(elem: Int) = elem == (_:Int)
Upvotes: 4
Reputation: 108
I imagine the Set you are defining here is not a scala.immutable.Set trait right? Regarding the code, calling List(something)
basically calls the apply
method on the List
companion object to create an immutable List.
The function singletonSet
basically returns a higher order function that takes an element named x and returns a boolean, but I don't think that piece of code compiles as it is missing type information on the x parameter.
Upvotes: 0