2014-09-20 63 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