【问题标题】:Pattern Match on String in Scala [duplicate]Scala中字符串的模式匹配[重复]
【发布时间】:2014-09-20 23:33:02
【问题描述】:

如何在 Scala 中对字符串进行模式匹配:

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]

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

所以它支持String上的模式匹配。

如何在 Scala 中做到这一点?

【问题讨论】:

  • 我打算添加一个答案,但那个重复的问题很好地涵盖了它
  • 感谢您指出这个骗局。我的错误(但我很高兴我从即席的回答中学到了)

标签: scala haskell


【解决方案1】:

您可以使用提取器。 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

【讨论】:

  • 这不是一个真正的答案,而是一组建议
  • 我添加了提取器的实现。我认为现在这应该可以作为答案。
  • 是的。谢谢你。
【解决方案2】:

您可以简单地将其转换为列表:

"55".toList

【讨论】:

    猜你喜欢
    • 2018-05-30
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多