从List [(Char,Char)]到Object的奇怪类型转换 [英] Strange type conversion from List[(Char, Char)] to Object

查看:82
本文介绍了从List [(Char,Char)]到Object的奇怪类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Scala 2.9.2中有一个递归函数count,看起来像这样

I have a recursive function count in Scala 2.9.2 that looks like this

def count(traces: Seq[(Char, Char)], acc: (TP, TN, FP, FN)): (TP, TN, FP, FN) = {
  val (tp, tn, fp, fn) = acc
  traces match {
    case Nil => acc
    case ('(', '(')::rest => count(rest, (tp + 1, tn, fp, fn))
    case (')', ')')::rest => count(rest, (tp + 1, tn, fp, fn))
    case ('(', ')')::rest => count(rest, (tp, tn + 1, fp, fn))
    // ... exhaustive set of cases ...
  }
}

在输入Seq(('(', '('))时,该函数将引发以下MatchError:

On input Seq(('(', '(')) the function throws the following MatchError:

scala.MatchError: Vector(((,()) (of class scala.collection.immutable.Vector)

我研究了Scala控制台中的代码,对此进行了调查.

I investigated this by playing around with the code in the Scala console.

scala> val t = Seq(('a', 'b'), ('b', 'c'))
t: Seq[(Char, Char)] = List((a,b), (b,c))

scala> t match { case Nil => "h"; case ('a', 'b')::rest => rest }
res6: java.lang.Object = List((b,c))

scala> t1 match { case Nil => "h"; case ('a', 'b')::rest => rest }
scala.MatchError: List((b,c)) (of class scala.collection.immutable.$colon$colon)

似乎匹配('a', 'b')::rest(第二行)没有返回正确类型的对象,因为Seq[(Char, Char)]突然是类型java.lang.Object,Scala然后不知道如何匹配

It seems as if matching ('a', 'b')::rest (the second line) doesn't return an object of the correct type, since the Seq[(Char, Char)] is suddenly of type java.lang.Object which Scala then doesn't know how to match on.

什么解释了这种行为?

推荐答案

模式匹配的问题是您使用提取器 仅定义列表类,但将其传递给他们.

The problem with your pattern matching is that you use extractors defined only for List class but passing to them Vector.

如果您确实需要与每个可能的Seq相匹配,则可能需要使用常规语法:

If you really need to match against every possible Seq, you may want to use general syntax:

   foo match {
     case Seq('(' -> ')',rest@ _* ) => println("The tail is" + rest)
   }

(不要与->箭头混淆,1 -> 2本质上与(1,2)相同,但是在这种特殊情况下,可读性更高:您不会将'('')'的大括号弄乱就像在Seq(('(',')'), ... ))

(Don't be confused with -> arrow, 1 -> 2 is essentially the same as (1,2), but in this particular case much more readable: you will not mess usual braces with '(' and ')' like in Seq(('(',')'), ... ))

否则,只需严格您的论点键入List [(Char,Char)].

Otherwise, just strict your argument type to List[(Char, Char)].

这篇关于从List [(Char,Char)]到Object的奇怪类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆