2014-09-20 45 views
0

我怎么能在斯卡拉字符串模式匹配:模式匹配的字符串在斯卡拉

scala> "55" match { 
    | case x :: _ => x 
    | } 
<console>:9: error: constructor cannot be instantiated to expected type; 
found : scala.collection.immutable.::[B] 
required: String 
       case x :: _ => x 
        ^

在Haskell一个String是char [Char]的列表:

Prelude> :i String 
type String = [Char] -- Defined in `GHC.Base' 

所以它支持模式匹配在String

我该如何在Scala中做到这一点?

+0

我要补充一个答案,但重复的问题涵盖了很好 – 2014-09-20 15:25:18

+0

谢谢你指出这件事。我的错误(但我很高兴从extempore的回答中学到) – 2014-09-20 15:27:11

回答

4

您可以使用提取。斯卡拉允许你建立自己的解构功能,最多SeqLike集合报价+:它的工作原理就像::List,遗憾的是String没有这个运营​​商的解构,只为建设。

但是你可以定义自己的提取为String这样的:

object %:: { 
    def unapply(xs: String): Option[(Char, String)] = 
     if (xs.isEmpty) None 
     else Some((xs.head, xs.tail)) 
    } 

用法:

scala> val x %:: xs = "555" 
x: Char = 5 
xs: String = 55 
+0

这不是一个真正的答案,而是一组建议 – 2014-09-20 15:19:02

+1

我已经添加了提取器的实现。我认为现在应该有资格作为答案。 – bmaderbacher 2014-09-20 15:34:24

+0

是的。感谢那。 – 2014-09-20 18:17:58

1

你可以简单地把它转换成一个列表:

"55".toList