0

I have a very simple example of a set s1 {1, 2} and I want to apply a predicate p > 1 on it. Now I have implemented this function, and it is giving me correct results.

  def filter(s: Set, p: Int => Boolean): Set = {(i: Int) => s(i) && p(i)}

Where definition of set is

  type Set = Int => Boolean

But is there a more elegant way of doing it in Scala?

6
  • I guess you have a good reason to define Set like this and not use standard Scala collection library?
    – ghik
    Oct 6, 2013 at 11:55
  • Yes, it is part of Martin Odersky's Coursera course assignment. Oct 6, 2013 at 11:58
  • @user1343318 You can drop the {} and the type annotation after i, so the body would look like this: i => s(i) && p(i). Other than that it looks fine... :) Oct 6, 2013 at 12:28
  • Scala doesn't have built-in predicates support (i.e. boolean logic), but it's easy enough to write your own combinators (timepit.eu/~frank/blog/2012/08/combining_predicates_in_scala) or import a library (github.com/wheaties/Predicates) if necessary. For your purposes your answer is fine. Oct 6, 2013 at 12:42
  • Can you be more precise with the question. Why do you think this is not elegant? You can leave away the type annotation for i by the way, because it is inferred. def filter(s: Set)(p: Int => Boolean): Set = { i => s(i) && p(i) }
    – 0__
    Oct 6, 2013 at 15:26

1 Answer 1

5

Using this course's definition of what a Set is, your answer is very elegant.

Since the predicate is in fact a Set too, filter could have been much more terse by reusing the intersect function:

/**
 * Returns the intersection of the two given sets,
 * the set of all elements that are both in `s` and `t`.
 */
def intersect(s: Set, t: Set): Set = ???

/**
 * Returns the subset of `s` for which `p` holds.
 */
def filter(s: Set, p: Int => Boolean): Set = intersect(s, p)

I left the intersect implementation out because the Coursera Honor Code prevents sharing assignment answers.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.