Andrew Andrew - 1 year ago 36
Scala Question

Assignment help: Union between sets

I am taking a Coursera Functional Programming in Scala class. This is the second week and I hit a wall. In the assignment we are working with Sets, but not the kind of Set we all meet in Java, for example. It is a Set that returns true if the value is in there and false otherwise. They say it's not a container, it's just a function.

To get it clear, I need your help. I don't want you to solve my assignment, it's just an example that I want to get the idea of what I should do.

* We represent a set by its characteristic function, i.e.
* its `contains` predicate.
type Set = Int => Boolean

* Indicates whether a set contains a given element.
def contains(s: Set, elem: Int): Boolean = s(elem)

* Returns the set of the one given element.
def singletonSet(elem: Int): Set = Set(elem)

* Returns the union of the two given sets,
* the sets of all elements that are in either `s` or `t`.
def union(s: Set, t: Set): Set = ???

This is the code. In the
I guess the way to solve it is to return the
, right?

If that is good, how am I supposed to make the union between the two? I am not new to programming but I can't see any way to do it. Since I shouldn't return a "set" of numbers.

This is what another student told me about sets: "But all a "Set" is is a function that takes an Int and returns a Boolean (Int => Boolean). Any function that takes an Int and returns a Boolean fits the type 'Set'."

What I tried in the union function is to have something like:

def union(s: Set, t: Set): Set = (s | t) //value | not a member of Int => Boolean

Any help would be appreciated :)

Answer Source

It seems the wall you are hitting is that you are unfamiliar with defining functions in Scala. In this particular case you need to define functions of type Int => Boolean, they take an Int and return a Boolean.

Here are some examples of function literals of type Int => Boolean. Try them in the Scala console or the Scala IDE worksheet:

(x: Int) => true
(x: Int) => false
(x: Int) => x == 2
(x: Int) => x == 10
(x: Int) => x == 2 || x == 10
(x: Int) => x % 2 == 0

Then all you have to do for the assignment is to use the same syntax, starting with (x: Int) => and then translate the meaning of union, intersect, ... into the right hand side of the expression.

Part of learning is giving it a genuine effort. I believe you can resubmit the solution multiple times, so don't hesitate to submit and iterate if you don't get 10/10 on the first try. All you need is compiling code. Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download