Domanda

Example:

you have two lists ("categories"):

catLow  = [1,2,3,4,5]
catHigh = [6,7,8,9,10]

Using pattern matching, how do you decide whether

val x = 7

Is within the first list (category) or the second one?

That's the general problem. My specific problem is doing that but in my case X is within a list as in:

val l = [1,7,2,4]

and I want to match it against something like:

case catHigh :: tail // i.e. starts with a "high" number
case _ :: catLow :: tail // i.e. second element is a "low" number
// where "high" and "low" are example category names implemented as lists
È stato utile?

Soluzione 2

You could do something like this:

scala> class Cat( xs:Set[Int] ) {
  def unapply( x:Int ) = if ( xs contains x ) Some(x) else None
}
defined class Cat

scala> object CatLow extends Cat( Set(1,2,3,4,5) )
defined object CatLow

scala> object CatHigh extends Cat( Set(6,7,8,9,10) )
defined object CatHigh

scala> def decode( zs:List[Int] ):Unit = zs match {
  case Nil =>
  case CatLow(z)::tail =>
    println("Low  "+z)
    decode(tail)
  case CatHigh(z)::tail =>
    println("High "+z)
    decode(tail)
  case z::tail =>
    println("???? "+z)
    decode(tail) 
}
decode: (zs: List[Int])Unit

scala> decode( List(1,7,2,0,4) )
Low  1
High 7
Low  2
???? 0
Low  4

Altri suggerimenti

val lowSet = Set(1, 2, 3, 4, 5)
val highSet = Set(6, 7, 8, 9, 10)

someList match {
  case catHigh :: tail if highSet(catHigh) => ...
  case _ :: catLow :: tail if lowSet(catLow) => ...
}

A Set can be used as a function that returns whether the passed element is in the Set. Then, in the match statement, you can use pattern guards (introduced with if) to check whether matched values are in the set.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top