開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Scala (プログラミング言語)
Learning Scala: Practical Functional Programming for the JVM (Jason Swartz (著)、O'Reilly Media)のPart Ⅰ. (Core Scala)、Chapter 6.(Common Collections)、Exercises 6.(No. 2481)を解いてみる。
その他参考書籍
Exercises 6.(No. 2481)
コード(Emacs)
#!/usr/bin/env scala-2.11
def palindromesWithPartition(strs:List[String]):(List[String], List[String]) = {
strs partition (str => str == str.reverse)
}
def palindromesWithFold(strs:List[String]): (List[String], List[String]) = {
strs.foldLeft((List[String](), List[String]()))(
(t, str) =>
if (str == str.reverse) (t._1 :+ str, t._2)
else (t._1, t._2 :+ str)
)
}
val strings: List[String] =
List("racecar", "Scala", "abba", "C", "JavaScript", "Python", "scala")
println(palindromesWithPartition(strings))
println(palindromesWithFold(strings))
入出力結果(Terminal, REPL(Read, Eval, Print, Loop))
$ ./sample6.scala (List(racecar, abba, C),List(Scala, JavaScript, Python, scala)) (List(racecar, abba, C),List(Scala, JavaScript, Python, scala)) $
0 コメント:
コメントを投稿