2015年10月28日水曜日

開発環境

  • 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 4.(No. 2481)を解いてみる。

その他参考書籍

Exercises 4.(No. 2481)

コード(Emacs)

#!/usr/bin/env scala-2.11

def longestWithFold(strings: List[String]): String = {
  strings.fold("")(
    (init:String, str:String) => if (init.length < str.length) str else init
  )
}
def longestWithReduce(strings: List[String]): String = {
  strings.reduce(
    (a:String, b:String) => if (a.length > b.length) a else b
  )
}

def maxWithFold[A](items: List[A], max:(A, A) => A): A = {
  items.fold(items(0))(
    (init:A, a:A) => max(init, a)
  )
}
def maxWithReduce[A](items: List[A], max:(A, A) => A): A = {
  items.reduce(
    (a:A, b:A) => max(a, b)
  )
}

def maxStr(a:String, b:String): String = if (a.length > b.length) a else b
def maxNum(a:Int, b:Int): Int = if (a > b) a else b

val strings: List[String] = List("Scala", "C", "JavaScript", "Python", "scala")
val nums = List(8, 0, 6, 2, 4, 9, 1, 7, 3, 5)

println(longestWithFold(strings))
println(longestWithReduce(strings))

println(maxWithFold(strings, maxStr))
println(maxWithFold(nums, maxNum))

println(maxWithReduce(strings, maxStr))
println(maxWithReduce(nums, maxNum))

入出力結果(Terminal, REPL(Read, Eval, Print, Loop))

$ ./sample4.scala
JavaScript
JavaScript
JavaScript
9
JavaScript
9
$

0 コメント:

コメントを投稿