Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

pattern match weird behavior with scala 2.13.4

I have the following code and my issue is with the DropWhile Function for which the compiler complain and i can't really understand why, especially given the realease notes of scala 2.13.4 https://github.com/scala/scala/releases

sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]

object List {

    @tailrec
    def dropWhile[A](list: List[A], f: A => Boolean): List[A] = list match {
        case Nil => Nil
        case Cons(s, xs) if f(s) => dropWhile(xs, f)
        case Cons(s, xs) if !f(s) => xs
    }

}

On line 35: warning: match may not be exhaustive. It would fail on the following input: Cons(_, _)

Is it a bug or limitation or am I not seeing something ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks to @user comment on the last guard, and after reviewing the release notes i caught the part that i missed:

The following types of matches no longer disable exhaustivity checking:

guards (case <pattern> if <condition> => ...) #9140

.........

New warnings reported can be resolved by:

adding any missing cases
in the case of complementary guards (e.g. if n > 0 and if n <= 0) by dropping the last guard
..........

EDIT1

Based on @sarveshseri, @Mateusz Kubuszok further comments above, This is definitely not a bug, but rather an intrinsic compilers limit. Doubled checked it in haskell and the warning is exactly the same

aDropWhile :: Num a => [a] -> (a -> Bool) -> [a]
aDropWhile [] _ = []
aDropWhile (s:xs) f 
  | f s = aDropWhile xs f
  | not (f s) = xs

warning:?[-Wincomplete-patterns] ????Pattern?match(es)?are?non-exhaustive ????In?an?equation?for?‘aDropWhile’:?Patterns?not?matched:?(_:_)?_

Note: My haskell is basic


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...