I just curious.
I try to do pattern matching strings in Scala with Haskell way (as list of chars)
As an example, this function that remove first "/" character in string:
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
}
usage:
println(filterFirstSlash("/test"))
Can I remove the leading slash using patter-matching? Is this good to do it in this way?
upd
this will remove all entries in head and tail:
def removeAllSlashes: Function[List[Char], String] = {
case Nil => ""
case '/' :: xs => removeAllSlashes(xs)
case xs :+ '/' => removeAllSlashes(xs)
case xs => xs
}
this will remove first entries only:
def removeFirstSlash: Function[List[Char], String] = {
case Nil => ""
case ('/' :: xs) :+ '/' => xs
case '/' :: xs => xs
case xs :+ '/' => xs
case xs => xs
}
p.s. Do not take it so seriously. This is just for fun. Thanks to everyone involved in the discussion.
replaceFirstand pass regex^\\/..Also look here stackoverflow.com/questions/21545933/… - Raj Parekh[regex]tag, because this seems like one appropriate solution in this case. But I'm against removingpattern-matching, since "Why doesn't pattern matching work here" seems to be an important part of the question. - Andrey Tyukin