1

I have some code like below. But I wish to avoid this mutable variable flag.

How can I achieve this?

  def map(s: Set, f: Int => Int): Set = (x: Int) =>  {
    var flag : Boolean = false
    for(i <- -bound to bound) {
      if(s(i) && f(i) == x){
        flag = true
      }
    }
    flag
  }
2
  • I don't know scala at all, but I image you could use a while loop instead of a for loop. while(!s(i) || f(i)!=x) Commented Sep 27, 2012 at 7:18
  • Yes this is a coursera question, and it should be solved with a simple one-liner, not a loop (not that that matters to the question as such). Commented Sep 27, 2012 at 8:59

2 Answers 2

5

I think you need this simple test:

(-bound to bound) exists {i => s(i) && f(i) == x}
Sign up to request clarification or add additional context in comments.

Comments

3

Use the exists collection method. The exists method returns true if the specified condition is true for at least one element in the collection, and false otherwise.

def map(s: Set[Int], f: Int => Int): (Int => Boolean) =
  (x: Int) => {
    (-bound to bound).exists(i => s(i) && f(i) == x)
  }

1 Comment

While I really don't want to support giving away solutions, I would at least want to give a pointer towards a better one: The hint about using exists is good. If exists is implemented as required in the assignment, it calls foreach, which already loops from -bound to bound. TL;DR: Aim at a ~25 char solution which does not require extra iteration but does the trick in the function it passes to exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.