Andrew - 5 months ago 23

Scala Question

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

`singletonSet`

`Set(elem)`

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: "

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!