Created
December 29, 2013 07:47
-
-
Save hideshi/8168406 to your computer and use it in GitHub Desktop.
This is the Scala oneliner library. This make you feel easy when you code oneliner on the command line. See also: http://d.hatena.ne.jp/hideshi_o/20120501/1335886709
This file contains 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
import scala.sys.process._ | |
import scala.io.Source._ | |
def in:List[String] = scala.io.Source.stdin.getLines.toList | |
implicit def pathToFileReader(path:String) = new FileReader(path) | |
class FileReader(path:String) { | |
def getLines():List[String] = { | |
try { | |
fromFile(path).getLines().toList | |
} catch { | |
case e:Exception => Console.err.print(e) | |
List[Nothing]() | |
} | |
} | |
def getl():List[String] = { | |
this.getLines() | |
} | |
} | |
implicit def listToConsoleWriter(lines:List[Any]) = new ConsoleWriter(lines) | |
class ConsoleWriter(lines:List[Any]) { | |
def printLines():Unit = { | |
lines.foreach(println(_)) | |
} | |
def ps():Unit = { | |
this.printLines() | |
} | |
} | |
def p(arg:Any) { | |
println(arg) | |
} | |
object File { | |
def apply(path:String):java.io.File = { | |
new java.io.File(path) | |
} | |
} | |
implicit def stringToFields(line:String) = new Fields(line) | |
var fs:String = "," | |
class Fields(line:String) { | |
def $(index:Int):String = { | |
try { | |
(line split fs)(index - 1) | |
} catch { | |
case e:ArrayIndexOutOfBoundsException => "" | |
} | |
} | |
} | |
implicit def listToOperateEachElementInList(lines:List[String]) = new OperateEachElementInList(lines) | |
class OperateEachElementInList(lines:List[String]) { | |
def substitute(from:String, to:String):List[String] = { | |
lines.map(s => s.replace(from, to)) | |
} | |
def extract(from:Int, to:Int):List[String] = { | |
lines.zipWithIndex.filter(t => if(t._2 >= (from - 1) && t._2 <= (to - 1)) true else false).map(t => t._1) | |
} | |
def substring(from:Int, to:Int):List[String] = { | |
lines.map(s => s.substring(from, to)) | |
} | |
def sampling(interval:Int):List[String] = { | |
lines.zipWithIndex.filter(t => if(t._2 % interval == 0) true else false).map(t => t._1) | |
} | |
def top(num:Int):List[String] = { | |
lines.zipWithIndex.filter(t => if(t._2 < num) true else false).map(t => t._1) | |
} | |
def bottom(num:Int):List[String] = { | |
lines.reverse.zipWithIndex.filter(t => if(t._2 < num) true else false).map(t => t._1).reverse | |
} | |
def grep(regex:String):List[String] = { | |
lines.filter(s => regex.r.findFirstIn(s).getOrElse("") != "") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment