Scala: Pattern matching when one of two items meets some condition

前端 未结 6 1818
野趣味
野趣味 2021-02-20 12:53

I\'m often writing code that compares two objects and produces a value based on whether they are the same, or different, based on how they are different.

So I might writ

6条回答
  •  庸人自扰
    2021-02-20 13:31

    If you have to support arbitrary predicates you can derive from this (which is based on Daniel's idea):

    List(v1, v2) filter (_ %2 == 0) match {
        case List(value1, value2) => "a"
        case List(value) => "b"
        case _ => "c"
    }
    

    the definition of the function:

    def filteredMatch[T,R](values : T*)(f : T => Boolean)(p: PartialFunction[List[T], R]) : R = 
        p(List((values filter f) :_* ))
    

    Now you can use it like this:

    filteredMatch(v1,v2)(_ %2 == 0){
        case List(value1, value2) => "a"
        case List(value) => "b"
        case _ => "c"
    }
    

    I'm not so sure if it's a good idea (i.e. readable). But a neat exercise nonetheless.

    It would be nice if you could match on tuples: case (value1, value2) => ... instead of lists.

提交回复
热议问题