Last active
September 12, 2016 09:23
-
-
Save skoky/5044da1c34a28fde6b4a6b2d032bbc7e to your computer and use it in GitHub Desktop.
Split string by 2 characters in Scala - simple, functional, great :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def spl(s:String) : List[String] = { | |
if (s.length>0) { | |
val x = s.splitAt(2) | |
x._1 :: spl(x._2) | |
} else Nil | |
} | |
val x = spl("010203") | |
>>>> x: List[String] = List(01, 02, 03) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// a @tailrec version
import scala.annotation.tailrec
def spl(expr: => String) = {
@tailrec
def iter(s: String, acc: List[String]): List[String] = {
if (s.length == 0) acc
else {
val x = s.splitAt(2)
iter(x._2, acc ++ List(x._1))
}
}
iter(expr, Nil)
}
spl("xxyyzz")