val1 before vals in scala varargs - scala

Here is an example from the Programming Scala book:
// src/main/scala/progscala2/patternmatching/match-vararglist.sc
// Operators for WHERE clauses
object Op extends Enumeration { // <1>
type Op = Value
val EQ = Value("=")
val NE = Value("!=")
val LTGT = Value("<>")
val LT = Value("<")
val LE = Value("<=")
val GT = Value(">")
val GE = Value(">=")
}
import Op._
// Represent a SQL "WHERE x op value" clause, where +op+ is a
// comparison operator: =, !=, <>, <, <=, >, or >=.
case class WhereOp[T](columnName: String, op: Op, value: T) // <2>
// Represent a SQL "WHERE x IN (a, b, c, ...)" clause.
case class WhereIn[T](columnName: String, val1: T, vals: T*) // <3>
val wheres = Seq( // <4>
WhereIn("state", "IL", "CA", "VA"),
WhereOp("state", EQ, "IL"),
WhereOp("name", EQ, "Buck Trends"),
WhereOp("age", GT, 29))
for (where <- wheres) {
where match {
case WhereIn(col, val1, vals # _*) => // <5>
val valStr = (val1 +: vals).mkString(", ")
println (s"WHERE $col IN ($valStr)")
case WhereOp(col, op, value) => println (s"WHERE $col $op $value")
case _ => println (s"ERROR: Unknown expression: $where")
}
}
I don't understand why there must be a val1 before vals, so I modified the code a bit:
// Represent a SQL "WHERE x IN (a, b, c, ...)" clause.
case class WhereIn[T](columnName: String, vals: T*) // <3>
val wheres = Seq( // <4>
WhereIn("state", "IL", "CA", "VA"),
WhereOp("state", EQ, "IL"),
WhereOp("name", EQ, "Buck Trends"),
WhereOp("age", GT, 29))
for (where <- wheres) {
where match {
case WhereIn(col, vals # _*) => // <5>
val valStr = vals.mkString(", ")
println (s"WHERE $col IN ($valStr)")
case WhereOp(col, op, value) => println (s"WHERE $col $op $value")
case _ => println (s"ERROR: Unknown expression: $where")
}
}
Well, this gives exactly the same output. Is there any good reason why the author added val1?

Given that the match using vals # _* can contain 0 or more entries, that initial variable has the effect of enforcing that at least one value has to be provided.
This blog entry details a similar trick relating to method arguments

Related

understand the use of _ in lift method_ [duplicate]

I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.
The ones I can think of are
Existential types
def foo(l: List[Option[_]]) = ...
Higher kinded type parameters
case class A[K[_],T](a: K[T])
Ignored variables
val _ = 5
Ignored parameters
List(1, 2, 3) foreach { _ => println("Hi") }
Ignored names of self types
trait MySeq { _: Seq[_] => }
Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }
Wildcard patterns in interpolations
"abc" match { case s"a$_c" => }
Sequence wildcard in patterns
C(1, 2, 3) match { case C(vs # _*) => vs.foreach(f(_)) }
Wildcard imports
import java.util._
Hiding imports
import java.util.{ArrayList => _, _}
Joining letters to operators
def bang_!(x: Int) = 5
Assignment operators
def foo_=(x: Int) { ... }
Placeholder syntax
List(1, 2, 3) map (_ + 2)
Method values
List(1, 2, 3) foreach println _
Converting call-by-name parameters to functions
def toFunction(callByName: => Int): () => Int = callByName _
Default initializer
var x: String = _ // unloved syntax may be eliminated
There may be others I have forgotten!
Example showing why foo(_) and foo _ are different:
This example comes from 0__:
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs # _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
1_000_000 // Numeric literal separator (Scala 2.13+)
This is also part of this question.
An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.
Examples:
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))
In Scala, _ acts similar to * in Java while importing packages.
// Imports all the classes in the package matching
import scala.util.matching._
// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and _= is added for the setter name.
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
Usage:
val t = new Test
t.age = 5
println(t.age)
If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
There is one usage I can see everyone here seems to have forgotten to list...
Rather than doing this:
List("foo", "bar", "baz").map(n => n.toUpperCase())
You could can simply do this:
List("foo", "bar", "baz").map(_.toUpperCase())
Here are some more examples where _ is used:
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums filter (_ % 2 == 0)
nums reduce (_ + _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)
Besides the usages that JAiro mentioned, I like this one:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
If someone needs all connection properties, he can do:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
If you need just a host and a port, you can do:
val ( host, port, _, _ ) = getConnectionProps
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”

Scala: conditional yield with matching and side-effects?

What is the correct syntax for something like the following?
var foo = 0
someIterator.foreach{ x => x.property match {
case "a" => foo += 1
case "b" => yield "current foo" + foo
}}
I.e., I'm trying to iterate over someIterator. When it matches one thing, it should update a local variable via closure; when it encounters another, it should yield some derivation of the current state to the resulting iterator preserving the state for successive iterations.
You can use Option[String], unlift and collect.
unlift takes a function that returns an option and turns it into a partial function.
collect is like map, except it considers only the elements for which the partial function is defined.
The following example demonstrates the approach:
import Function.unlift
var foo = 0
someIterator.map(_.property).collect(unlift {
case "a" => foo += 1; None
case "b" => Some("current foo" + foo)
})
Live Demo
If you just want to have the final value of foo then you can use tail recursion and you won't have to use a mutable variable too.
#annotation.tailrec
def f(l: List[Char], foo: Int = 0):Int= {
if (l == Nil) foo
else {
l.head match {
case 'a' => f(l.tail, foo + 1)
case 'b' => f(l.tail, foo)
}
}
}
val l1 = List('a','b')
f(l1)
l1: List[Char] = List(a, b)
res0: Int = 1
You can use scanLeft's acumulator instead of variable:
someIterator.scanLeft((0, None: Option[String])){
case ((foo, _), "a") => (foo + 1, None)
case ((foo, _), "b") => (foo, Some(s"current foo $foo"))
}.map(_._2).flatten
Example:
val someIterator = List("a","a","a","a","b", "a", "a", "b").toIterator
scala> someIterator.scanLeft(...){...}.map(_._2).flatten
res16: Iterator[String] = non-empty iterator
scala> res16.toList
res17: List[String] = List(current foo 4, current foo 6)
So you still have an iterator as a result

Chaining partial functions with match statements

I am trying to factor out common behaviour from long pattern matching statements to DRY my code out. The idea is to chain the common code in partial functions and have that evaluated by the match statement. My ideal is something like
type pf = PartialFunction[Int, String]
// Our common behaviour
val common: pf = {
case 0 ⇒ "zero"
case 1 ⇒ "one"
}
val a = 2
// speculative match statement with extended behaviour
val b = a match (common orElse {
case 2 ⇒ "two"
case 3 ⇒ "three"
case _ ⇒ "None"
})
Unfortunately, the argument to the match statement is apparently not a partial function. Obviously, the problem can be solved using partial functions, the code below doing the trick but I lose out on the conventional pattern match syntax:
val c: String = (common orElse {
case 2 ⇒ "two"
case 3 ⇒ "three"
case _ ⇒ "None"
}: pf)(a)
The example below is on the ugly side of what I am looking for. It compiles but fails with a scala.MatchError if the argument a is not defined in the common partial function.
val d = common(a) orElse (a match {
case 2 ⇒ "two"
case 3 ⇒ "three"
case _ ⇒ "None"
})
I am looking for the following answers:
Why is the argument to the match statement not translated into partial function?
Why does the ugly example above fail?
Is there a clever way to achieve the goal?
Match has not been generalized as for catch, most recently here:
https://github.com/scala/scala/pull/4334
where you can supply a partial function to a catch.
The catch is easy in that it must be a PartialFunction[Throwable, ?], but it's not obvious to me that pattern matches generalize in the same way. At issue are exhaustiveness checks, the expected type of the scrutinee, who knows what.
What's wrong with this...?
type Pfis = PartialFunction[Int, String]
val common: Pfis = {
case 0 ⇒ "zero"
case 1 ⇒ "one"
}
val a = 2
val other: Pfis = {
case 2 ⇒ "two"
case 3 ⇒ "three"
case _ ⇒ "None"
}
val b = ( common orElse other )( a )
// If you feel like using the "conventional match-case"
val f = common orElse other
val c = a match { case x => f( x ) }
Also, there is no such thing as conventional pattern matching syntax... match is a keyword which "can be thought to act" as a right-associative function which means that a match pf is very much same ( not really same... a match pf does not work) as pf.apply( a ) or just pf( a ).
Also, orElse is a used for functional-composition so basically, you compose a new partial-function by orElseing two partitial-functions. Then you call this new parital-function, the same way as you would use any partial-function.
I think, if you understand what orElse does... you will understand the answer to your second point. Well, it fails because you are applying the partial-function common for argument 2 and it is not defined at 2.
Also, one more thing... even if common was defined at a, you are doing something very wrong. Let me explain,
val t = 1
val d = common( t ) orElse ( t match {
case 2 ⇒ "two"
case 3 ⇒ "three"
case _ ⇒ "None"
})
// Now d is same as following,
val k = "one" orElse "None"
// Here, k and d both are actually PartialFunction[Int,Char] = <function1>
// basically, both k and d take an Int i as argument and return the ( character at index i in "one" ) orElse ( character at index i in "None" )
// So,
println( d( 2 ) )
// Will print - e
println( d( 3 ) )
// since "one" does not have index 3, it will return index 3 in "None"
// will print - e
println( d( 4 ) )
// None of "one" and "None" have index 4
// So, you will get - scala.MatchError: 4 (of class java.lang.Integer)

what does underscore mean in scala [duplicate]

I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.
The ones I can think of are
Existential types
def foo(l: List[Option[_]]) = ...
Higher kinded type parameters
case class A[K[_],T](a: K[T])
Ignored variables
val _ = 5
Ignored parameters
List(1, 2, 3) foreach { _ => println("Hi") }
Ignored names of self types
trait MySeq { _: Seq[_] => }
Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }
Wildcard patterns in interpolations
"abc" match { case s"a$_c" => }
Sequence wildcard in patterns
C(1, 2, 3) match { case C(vs # _*) => vs.foreach(f(_)) }
Wildcard imports
import java.util._
Hiding imports
import java.util.{ArrayList => _, _}
Joining letters to operators
def bang_!(x: Int) = 5
Assignment operators
def foo_=(x: Int) { ... }
Placeholder syntax
List(1, 2, 3) map (_ + 2)
Method values
List(1, 2, 3) foreach println _
Converting call-by-name parameters to functions
def toFunction(callByName: => Int): () => Int = callByName _
Default initializer
var x: String = _ // unloved syntax may be eliminated
There may be others I have forgotten!
Example showing why foo(_) and foo _ are different:
This example comes from 0__:
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs # _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
1_000_000 // Numeric literal separator (Scala 2.13+)
This is also part of this question.
An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.
Examples:
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))
In Scala, _ acts similar to * in Java while importing packages.
// Imports all the classes in the package matching
import scala.util.matching._
// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and _= is added for the setter name.
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
Usage:
val t = new Test
t.age = 5
println(t.age)
If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
There is one usage I can see everyone here seems to have forgotten to list...
Rather than doing this:
List("foo", "bar", "baz").map(n => n.toUpperCase())
You could can simply do this:
List("foo", "bar", "baz").map(_.toUpperCase())
Here are some more examples where _ is used:
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums filter (_ % 2 == 0)
nums reduce (_ + _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)
Besides the usages that JAiro mentioned, I like this one:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
If someone needs all connection properties, he can do:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
If you need just a host and a port, you can do:
val ( host, port, _, _ ) = getConnectionProps
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”

What are all the uses of an underscore in Scala?

I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of “_”?". Can you? If yes, please do so here. Explanatory examples are appreciated.
The ones I can think of are
Existential types
def foo(l: List[Option[_]]) = ...
Higher kinded type parameters
case class A[K[_],T](a: K[T])
Ignored variables
val _ = 5
Ignored parameters
List(1, 2, 3) foreach { _ => println("Hi") }
Ignored names of self types
trait MySeq { _: Seq[_] => }
Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }
Wildcard patterns in interpolations
"abc" match { case s"a$_c" => }
Sequence wildcard in patterns
C(1, 2, 3) match { case C(vs # _*) => vs.foreach(f(_)) }
Wildcard imports
import java.util._
Hiding imports
import java.util.{ArrayList => _, _}
Joining letters to operators
def bang_!(x: Int) = 5
Assignment operators
def foo_=(x: Int) { ... }
Placeholder syntax
List(1, 2, 3) map (_ + 2)
Method values
List(1, 2, 3) foreach println _
Converting call-by-name parameters to functions
def toFunction(callByName: => Int): () => Int = callByName _
Default initializer
var x: String = _ // unloved syntax may be eliminated
There may be others I have forgotten!
Example showing why foo(_) and foo _ are different:
This example comes from 0__:
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs # _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
1_000_000 // Numeric literal separator (Scala 2.13+)
This is also part of this question.
An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.
Examples:
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))
In Scala, _ acts similar to * in Java while importing packages.
// Imports all the classes in the package matching
import scala.util.matching._
// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and _= is added for the setter name.
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
Usage:
val t = new Test
t.age = 5
println(t.age)
If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
There is one usage I can see everyone here seems to have forgotten to list...
Rather than doing this:
List("foo", "bar", "baz").map(n => n.toUpperCase())
You could can simply do this:
List("foo", "bar", "baz").map(_.toUpperCase())
Here are some more examples where _ is used:
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums filter (_ % 2 == 0)
nums reduce (_ + _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)
Besides the usages that JAiro mentioned, I like this one:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
If someone needs all connection properties, he can do:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
If you need just a host and a port, you can do:
val ( host, port, _, _ ) = getConnectionProps
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”