Skip to content

Instantly share code, notes, and snippets.

@kencharos
Last active December 17, 2015 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kencharos/5574941 to your computer and use it in GitHub Desktop.
Save kencharos/5574941 to your computer and use it in GitHub Desktop.
Scala memo
// scala snippets
// read STDIO examples.
// read single line.
def singleLine():String={
readLine()
}
// read from redirect(e.g, scala Test.scala < some.txt)
def simpleExample():Seq[String]={
scala.io.Source.stdin.getLines.toList
}
// use Iteraoter#continually
def fpLikeExample():Seq[String] = {
Iterator.continually(readLine()).takeWhile(_ != null).toList
}
// java like exapmle (don't use)
def whileExample():Seq[String] = {
var line = readLine()
var result = Seq[String]()
while (line != null) {
result = result :+ line
line = readLine()
}
result
}
// read From file
def readFile(name:String) = {
scala.io.Source.fromFile(name).getLines
// scala.io.Source.fromFile(name)("utf-8").getLines // consider charset.
}
// write to file
def writeFile(list:Traversable[String], name:String):Unit = {
import java.io.PrintWriter
val out = new PrintWriter(name)
list.foreach(out.println(_))
out.close
}
// write file with loan pattern(auto close.)
def write(path:String)(f:java.io.PrintWriter => Unit) {
val out = new java.io.PrintWriter(path)
try {
f(out)
} finally {
out.close()
}
}
// usage
//simple
write("sample.txt"){w => w.println("sample")}
// output line
val lines = List("line1", "line2", "line3")
write("sample2.txt"){lines foreach _.println}
// output lines with function
val outList = (list:Iterable[String]) => (out:java.io.PrintWriter) => list.foreach{out.println}
wriete("sample3.txt"){outList(lines)}
// String to collection, collention to String
val col = "222,333,444".split(",") // Array("222", "333", "444")
col mkString(",") // "222,333,444"
col mkString("[", "," , "]") // ["222,333,444"]
// String to Int, Double, etc toXXXXX
"5" toInt // 5
"5" toDouble // 5.0
// list
val list = List(1,2,4,6,8)
// indexed list
val indexedList = list.zipWithIndex.map{case (e, i) => (i, e) }
// fileter by index(e.g, get even index elements)
indexedList filter(_._1 % 2 == 0) map(_._2) // even index List(1,4,8)
// rewiter by collect
indexedList collect{case (i, e) if i % 2 == 0 => e}
// In case, refer previous list element. output each elements add
val slide = list zip list.tail // List((1,2), (2,4), (4,6), (6,8)
slide map{x => x._2 - x._1} // List((2-1), (4-2), (6-4), (8-6)) => List(1,2,2,2)
// grouped
val group = list grouped(2) // => List(List(1,2), List(4,6), List(8))
//list sum
list sum // 21
list.foldLeft(0)(_ + _) // 21
list.foldLeft("")(_ + _) // "12468"
// collection convert
list toSet // set
list.map(x => x -> x.toString).toMap // tupple list convert map
// regExp and pattern match, extract
case class YMD(year:String, month:String, day:String)
def getYMD(str:String):Option[YMD] = {
val pattern = "([0-9]{4})/([0-9]{2})/([0-9]{2})".r
str match {
case pattern(y,m,d) => Some(YMD(y,m,d))
case _ => None
}
}
println(getYMD("2012/01/01")) // Some(YMD(2012, 01, 01))
println(getYMD("2012/1/1")) // None
//function compsition
// Note! def and Function1 is not same.
def len(s:String) = s.length // def is Method Tyoe.
val len_ = (s:String) => s.length // (String) => Int<Function> is FunctionType
// val len2 = len // compile error.
val len2 = len _ // OK len2 is FUnctionType
len2("123") // 3
def read(str:String) = str.split("\n")
def count(list:Array[String]) = list size
// output lines count
// method chain. f(g(x)) many brace.
def lineCount(str:String) = count(read(str))
// compose f compose g => f(g(x))
// compose is Function trait method. def is convert to Function
val lineCountComp = (count _) compose (read _)
// antThen f andThen g => g(f(x))
val lineCountAndThen = read _ andThen count _
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment