user1343318
user1343318

Reputation: 2141

Scala and Writing map functions

So suppose I have a function that expects a Set with definition Int => Boolean and a function f like this:

def map(s: Set, f: Int => Int): Set = {}

Now how do I apply this f to each element of this set s.

def map(s: Set, f: Int => Int): Set = { (i: Int) => f(s(i)) }

Which is ofcourse incorrect because in f(s(i)), 's(i)' returns a boolean, and thus can't apply f on it. Problem is how do I access each element of Set and apply this f on it?

This question is part of Coursera's Functional Programming with Scala course.

Upvotes: 4

Views: 3007

Answers (3)

user3685285
user3685285

Reputation: 6566

If you wrote the exists function correctly:

def map(s: Set, f: Int => Int): Set = (i: Int) => exists(s, (x: Int) => i == f(x))

Bam one line!

Upvotes: 1

Harshal Pandya
Harshal Pandya

Reputation: 1624

You need to use fold to do this.

def map(s: Set[Int], f: Int => Int): Set[Int] = 
    s.foldLeft(Set.empty[Int])((s,i) => s+f(i))

Upvotes: -2

maasg
maasg

Reputation: 37435

A goal of the course is to help you understand the functional model, and in this case, how the Set can be represented by a function (called the charasteristic function for that set).

Instead of the final solution, here's a hint on how to reason about this problem:

Given the characteristic function f: Int => Boolean that defines your set and x, an Int, if f(x) == true, then x belongs to the Set. Now, if you have a function g:Int=>Int that you want to map over the set, what you want is to apply that function to the elements that you know that belong to the set: if (f(x)) then g(x).

Try to apply that thinking to your exercise.

Upvotes: 5

Related Questions