Scala中字符串的模式匹配

时间:2014-09-20 14:26:08

标签: scala haskell

如何在Scala中对String进行模式匹配:

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中执行此操作?

2 个答案:

答案 0 :(得分:4)

您可以使用提取器。 Scala允许您构建自己的解构函数,大多数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

用法:

{{1}}

答案 1 :(得分:1)

您只需将其转换为列表:

"55".toList
相关问题