簡體   English   中英

Scala字符串上的Haskell樣式模式可以匹配嗎?

[英]Is Haskell-style pattern matching on Scala Strings possible?

我只是好奇

我嘗試使用Haskell方式在Scala中進行模式匹配字符串(作為字符列表)

例如,此函數刪除字符串中的第一個“ /”字符:

import scala.language.implicitConversions

implicit def stringToChars(s: String): List[Char] = s.toCharArray.toList

implicit def charsToString(a: List[Char]): String = a.mkString

def filterFirstSlash: Function[List[Char], String] = {
  case Nil => ""
  case '/' :: Nil => ""
  case '/' :: xs => xs
  case xs => xs
}

用法:

println(filterFirstSlash("/test"))

我可以使用模式匹配刪除前導斜線嗎? 以這種方式這樣做好嗎?

更新

這將刪除頭部和尾部的所有條目:

def removeAllSlashes: Function[List[Char], String] = {
    case Nil => ""
    case '/' :: xs => removeAllSlashes(xs)
    case xs :+ '/' => removeAllSlashes(xs)
    case xs => xs
}

這只會刪除第一個條目:

def removeFirstSlash: Function[List[Char], String] = {
    case Nil => ""
    case ('/' :: xs) :+ '/' => xs
    case '/' :: xs => xs
    case xs :+ '/' => xs
    case xs => xs
}

ps不要那么認真。 這只是為了好玩。 感謝參與討論的每個人。

不,那不是一個好方法。 String不是字符列表。 在JVM上,字符串是UTF-16代碼單元的不變數組。 它們與鏈接列表無關。 您的filterFirstSlash將始終忽略前三種情況,並始終返回不變的輸入。

要降低斜線,您可以執行以下操作:

"////abcd".dropWhile(_ == '/')  // returns `"abcd"`

要么

"/abcd".replaceAll("^/", "")

要么

((s: String) => if (s startsWith "/") s.tail else s )("/abcd")

或者,也許,如果您確實堅持模式匹配,則可以使用預編譯的正則表達式模式來匹配前導斜杠和字符串的其余部分:

val Rgx = "^/(.*)$".r
"/abcd" match { case Rgx(s) => s; case s => s }      // evaluates to `"abcd"`

從技術上講,這是可能的:

def filterFirstSlash(s: String) = {
  case '/' +: xs => xs
  case xs => xs
}

當然,效率不如鏈表的相同代碼,因為+:每次都會復制整個字符串,因此您不希望使用它來遞歸地挑選字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM