Frage

Full disclosure: I am (was?) taking Coursera's Scala course but was stumped by the second assignment on Sets. I'm not looking for just the answers (which are easily obtainable) and would receive marginal credit anyway. But I would really like to understand what is happening.

Okay, so here is the first question: "Define a function which creates a singleton set from one integer value: the set represents the set of the one given element." So my first attempt was this:

def singletonSet(elem: Int): Set = Set(elem)

So this function, singletonSet, just returns a newly created Set. It could be invoked thusly:

val why = singletonSet(3)
// now why is a singleton set with a single integer, 3

This implementation seemed trivial, so I Googled for the answer, which seems to be this:

def singletonSet(elem: Int): Set = (x => x == elem)

Now my understanding is that (x => x == elem) is an anonymous function which takes an integer x and returns a boolean. But... what? So as a JavaScript developer, I decided to translate it:

function singletonSet(elem) {
    return function(x) {
        return x === elem;
    };
};

So then I can write (am I currying?):

singletonSet(3)(4)

// singletonSet(3) => returns an anonymous function, function(x) { x === 3; };
// function(4) { return 4 === 3; }
// false

If this is even close to what is happening in Scala, it seems like I am not creating a singleton set. Rather, I am just checking if two numbers are the same.

What am I missing here? I feel like it must be something very basic.

Thanks in advance.

War es hilfreich?

Lösung

Remember this implementation of a set is a function. In particular its a boolean function, so the function can just be seen as asking the question: "Is this number in the set? - true or false." The function can be called as many times as you want, in effect asking the question multiple times:

"is this number in the set? Is that number in the set?" etc, etc.

As the set is a singleton set, there is only one number in the set. So you use the set by calling the function, asking the question, in effect, "is this number the one and only number that is in the set?" So you are correct this set, the singleton set is just asking are these two numbers the same.

It should be emphasised that this example is from the course Functional Programming Principles in Scala. The course is not meant as an easy introduction to Scala. In fact the course is deliberately making things difficult, in order to enable a deep understanding of functional programming. Normally one would just use the in scope immutable Set class.

If you wanted to work with say the even numbers between -1000 and 1000, you'd probably use an iterator like:

(-1000 to 1000).withFilter(_ %2 == 0)

or:

(-1000 to 1000 by 2)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top