Skip to content

Instantly share code, notes, and snippets.

@skoky
Last active September 12, 2016 09:23
Show Gist options
  • Save skoky/5044da1c34a28fde6b4a6b2d032bbc7e to your computer and use it in GitHub Desktop.
Save skoky/5044da1c34a28fde6b4a6b2d032bbc7e to your computer and use it in GitHub Desktop.
Split string by 2 characters in Scala - simple, functional, great :)
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)
@skoky
Copy link
Author

skoky commented Sep 12, 2016

// 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")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment