【发布时间】:2019-01-25 15:15:59
【问题描述】:
我只是好奇。
我尝试使用 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
}
附言 不要那么认真。 这只是为了好玩。 感谢参与讨论的所有人。
【问题讨论】:
-
也许你可以使用
replaceFirst并通过正则表达式^\\/..也看看这里stackoverflow.com/questions/21545933/… -
@WiktorStribiżew 我回滚了,抱歉。如果您添加
[regex]标签,我可能会同意,因为在这种情况下,这似乎是一种合适的解决方案。但我反对删除pattern-matching,因为“为什么模式匹配在这里不起作用”似乎是问题的重要部分。 -
我知道正则表达式。这不是关于它。我的好奇心是 - 有可能以haskell方式做吗? :)