Skip to content

Instantly share code, notes, and snippets.

@SAMMY7th
Created February 8, 2018 13:40
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 SAMMY7th/d3df84c211497412558ccd0f16d90a09 to your computer and use it in GitHub Desktop.
Save SAMMY7th/d3df84c211497412558ccd0f16d90a09 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
import scala.collection.immutable.TreeMap
val lines = List(
"- 2018年02月08日 木曜日 20:51",
"今日は仕事をしました",
"お昼にパスタをつくりました",
"- 2018年02月09日 金曜日 20:51",
"お出かけしました"
)
val dateTimeSep = """- (\d\d\d\d)年(\d\d)月(\d\d)日 .曜日 (\d\d:\d\d)""".r
// foldLeft版
val articles = lines.foldLeft(TreeMap[String, String]()) { (_articles, line) =>
line match {
case dateTimeSep(year, month, day, time) =>
_articles.insert(s"$year-$month-$day $time", "")
case _ => {
val (lastKey, lastValue) = _articles.last
_articles.updated(lastKey, s"$lastValue$line\n")
}
}
}
println(articles)
// 再帰関数版
@tailrec
def convert(lines: List[String], articles: TreeMap[String, String]): TreeMap[String, String] = {
lines match {
case (head :: tail) =>
head match {
case dateTimeSep(year, month, day, time) =>
convert(tail, articles.insert(s"$year-$month-$day $time", ""))
case _ => {
val (lastKey, lastValue) = articles.last
convert(tail, articles.updated(lastKey, s"$lastValue$head\n"))
}
}
case Nil => articles
}
}
println(convert(lines, TreeMap[String, String]()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment