Scala Extra Return Function

I take Coursera FP Principles in a Scala course, and I am having problems with the last function in assigning week 2. I do not need an answer, but rather help in understanding the functional composition of Scala. I think that I have the right idea on how to solve the problem, I just worked on the Scala special part.

The bottom line is this: we were given a type alias that is defined as such:

type Set = Int => Boolean 

What I interpreted as Set is a function that takes an Int and returns a Bool.

We were also instructed to complete the singletonSet function, which takes an int and returns Set. I wrote it as such

 def singletonSet(x: Int): Set = Set(x) val three = singletonSet(3) three(3) //True three(5) //False 

I have a problem with a Map function that has this signature:

 def map(s: Set, p: Int => Int): Set 

Which I interpreted as a function that takes a set, converts its elements to a function P and returns a new set.

Pesudocode: Map returns a function that accepts int, and if int exists in Set s, return a new Set with converted int X (or p (x)

Actual code that breaks:

 def map(s: Set, p: Int => Int): Set = { x => if (s(x)) singletonSet(p(x)) else p(x) => false } The error that I'm getting with this format is: error: not a legal formal parameter. Note: Tuples cannot be directly destructured in method or function parameters. Either create a single parameter accepting the Tuple1, or consider a pattern matching anonymous function: `{ case (param1, param1) => ... } else p(x) => false 

I am not trying to understand what happened to my implementation. A friend wrote my logic in Haskell and found it successful, so I believe that my algorithm is correct (although I could be wrong). I am struggling with the details of the Scala implementation. Any advice or recommendations are greatly appreciated.

+6
source share
1 answer

Remember that you are dealing with Set here, and Set is defined as a function that converts Int to Boolean . Therefore, your function should return the same:

 def map(s: Set, p: Int => Int): Set = { x => if (s(x)) singletonSet(p(x)) // Returns a Set else p(x) => false // Returns a Boolean } 

We see that, despite the input, you have two different cases of inference, which, as we know, must be erroneous. Now let's also recall that you have other functions, and your definition of a set and “expand” what you are building:

 def map(s: Set, p: Int => Int): (Int) => (Boolean) //Expand 'Set' to int->boolean = (x: Int) => (Something that returns a boolean) 

Your task is to find out what this “something” is based on the semantics of map . I highly recommend looking at other functions that return a boolean and ask how they can be applied here. In particular, you are looking for a function that for any integer will provide you with a conversion if that integer exists in the source set.

+1
source

All Articles