1

I am a newbie in Scala. I have the following code to define a constant function that returns true for 1,2,3 and false for the other Integers.( actually the function defines a set {1,2,3} of integers):

val a= Node1 _
def Node1(x:Int):Boolean={
            if (x==1 || x ==2 || x==3){true}
            else{false}
}

Is there any way to define this function more concisely?

4
  • 3
    val a: Int => Boolean = Set(1, 2, 3) Jun 1, 2015 at 6:40
  • 1
    I case you can't use Set: val test = (_: Int) match { case 1 | 2 | 3 => true; case _ => false }
    – senia
    Jun 1, 2015 at 6:44
  • @Gábor Bakos How the code changes if I want to substitute Int with Any?
    – qartal
    Jun 1, 2015 at 6:44
  • Mathematically, a constant function is a function that always returns the same value regardless of the argument. This is not the case for your example.
    – ziggystar
    Jun 1, 2015 at 6:58

2 Answers 2

3
val a: Int => Boolean = Set(1, 2, 3).contains(_)

which is effectively same as

val a: Int => Boolean = Set(1, 2, 3)

This is because Set's apply method is same as its contains method.

3
  • 1
    The .contains(_) is superfluous. Jun 1, 2015 at 6:45
  • Can you please give a hint how the code changes if I want to substitute Int with Any? Should I just replace Int with Any in the code?
    – qartal
    Jun 1, 2015 at 6:49
  • Yes @qartal, val a: Any => Boolean = Set(1, 2, 3) works as you expect. Jun 1, 2015 at 6:52
0

On lookup performance, although as aforementioned Set.apply conveys the desired semantics, note that Set is a trait that may implement for instance ListSet, HashSet or TreeSet, each designed for specific uses.

For the aim here of looking up for an element, consider TreeSet (see Collections Performance Characteristics for details) outperforms other Set implementations. This proves relevant specially for large collections.

Your Answer

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

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