undisp
undisp

Reputation: 721

Scala: am I writing a curried function?

I have to transform the following function into a curried function:

def findAllUsed(t: List[Task]): List[String] = {
    t.flatMap(x => x.resources.map(x => x.FIELD_TO_SEARCH)).distinct
}

So I did this:

def findAllUsed(t: List[Task], f: Resource => String): List[String] = {
    t.flatMap(x => x.resources.map(f)).distinct
}
findAllUsed(taskSchedules, ((x: Resource) => { x.id }))
findAllUsed(taskSchedules, ((x: Resource) => { x.kind }))

The problem is that it seems to me that I am confusing currying with higher order functions.

Can anyone if I am doing it right and if not, how could I manage to do it right?

Upvotes: 0

Views: 151

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37852

I'm assuming the exercise meant something like this:

// separate into two argument lists
def findAllUsed(t: List[Task])(f: Resource => String): List[String] = {
  t.flatMap(x => x.resources.map(f)).distinct
}

// apply the first argument list once, 
// getting a curried function as a result
val curried = findAllUsed(taskSchedules)

// now you can use it twice with different inputs for the second argument list:
curried(x => x.id)
curried(x => x.kind)

The benefit here (if there is any), is the removal of the duplication passing taskSchedules to your function: since it has "it's own" argument list, you can pass it once, assign the result into a value (curried), and then reuse it over and over;

p.s. the type of curried is (Resource => String) => List[String] - it's a function from a Resource => String (which is another function...) to a list of strings.

Upvotes: 1

Related Questions