M4ks
M4ks

Reputation: 12024

Implicit String to Seq[Char] pattern matching fail

Warning - this is a code which deals with Codility BinaryGap task - just to warn as this may spoil something to somebody.

I have a piece of code, like

@tailrec
def count2(max:Int, count:Int, d:Seq[Char]):Int = d match {
  case '1' :: s => count2(Math.max(max, count), 0, s)
  case '0' :: s => count2(max, count+1, s);
  case Nil => max
}

I call it like

println(Solution.count2(0, 0, Seq('1', '0')))
println(Solution.count2(0, 0, "10"))

It compiles, however the second call does not work - throwing "Match not found 10" And I cannot understand why. There is a similar question around that topic which states, that explicit conversion is needed. However, I feel like I do have one in form of a method parameter type. Debugger clearly states that d variable is of type WrappedString - which should do the job. But apparently, it does not.

What is going on here?

Upvotes: 0

Views: 104

Answers (1)

wheaties
wheaties

Reputation: 35980

Your pattern matching is working only on a the type List[Char] while you are passing an object of type Seq[Char]. Therefore you will never actually match on the very first call. The reason it compiles is that match is not exhaustive for Seq. It is, however, exhaustive for List.

Update:

Let me point out two things:

  1. The default constructor for Seq produces a List. So the first example "works."
  2. The String you've given is implicitly convertable to a Seq[Char] but it is not a List! Hence, it will give you your match error.

Upvotes: 2

Related Questions