mCs - 8 months ago 125

Scala Question

We got three functions. The first one defines type alias for Boolean condition

`type Set = Int => Boolean`

I understand that this is the alias definition. Now the second fucntion

`def contains(set: Set, elem: Int): Boolean = set(elem)`

calls the

`(Int=>Boolean)`

`elem:Int`

**QUESTION 1**: Where is the logic of the function under?`Set`

- I mean, do I have to pass the function actual parameter (in which case the
`Set`

is a higher order function) when calling`contains`

eg. for even numbers set:`contains`

`val in:Boolean = contains({x=>(x%2)==0},2)`

In the third function:

`def singletonSet(elem: Int): Set = set => set == elem`

**Question 2:**Where does thecome form? Its not in the formal parameter list.`set`

Answer

**QUESTION 1:** Yes, you have to pass a `Set`

which would be the "implementation" of the function. The point of this exercise (Odersky's course?) is to show that a Set can be defined not as a collection of items (the "usual" definition of a set), but rather as a function that says whether an item is included in the set or not. So **the Set is the function**.

**QUESTION 2:** `set`

is the name given to the argument of the anonymous function we're returning here: Since `singletonSet`

's return type is `Set`

, which as we've said is actually a function of type `Int => Boolean`

, we return an (anonymous) function. To create such a function, one uses the syntax `x => f(x)`

, where `x`

is any name you'd like and `f(x)`

is an expression using it (or not).