99個のScalaの問題集

http://aperiodic.net/phil/scala/s-99/
S-99: Ninety-Nine Scala Problems

算数のドリルみたいな感じ。
ちょっと解いてみた。
エラー処理は、例外を吐くか、requireでブロックするか、戻り値をOptionにするか、など色々考えられるが、面倒なので無視する方向でwww。

P01 (*) Find the last element of a list.
最後の要素を返せ。
Example:
scala> last(List(1, 1, 2, 3, 5, 8))
res0: Int = 8
// 解1:最初に思いついたヤツ
def last(list:List[Any]):Any = list.reverse.head
// 解2:Javaっぽい従来の書き方
def last(list:List[Any]):Any = list(list.size-1)
// 解3:そのものがあった(^^;
def last(list.List[Any]):Any = list.last
P02 (*) Find the last but one element of a list.
最後から2番目を返せ。
Example:
scala> penultimate(List(1, 1, 2, 3, 5, 8))
res0: Int = 5
面倒くさい。パス1
P03 (*) Find the Kth element of a list.
By convention, the first element in the list is element 0.
リストのK番目の要素を返せ。最初の要素は0。
Example:
scala> nth(2, List(1, 1, 2, 3, 5, 8))
res0: Int = 2
// 解1:最初に思いついたヤツ
def nth(index:Int, list:List[Any]):Any = list(index)
// 解2:地道に作る
def nth(index:Int, list:List[Any]):Any = 
	if (index <= 0) list.head else nth(index-1, list.tail)
P04 (*) Find the number of elements of a list.
リストの要素の数を返せ。
Example:
scala> length(List(1, 1, 2, 3, 5, 8))
res0: Int = 6
// 解1:最初に思いついたヤツ
def length(list:List[Any]):Int = list.size
// 解2:地道に作る
def length(list:List[Any]):Int = 
	if (list == Nil) 0 else 1 + length(list.tail)
P05 (*) Reverse a list.
リストを反転させよ。
Example:
scala> reverse(List(1, 1, 2, 3, 5, 8))
res0: List[Int] = List(8, 5, 3, 2, 1, 1)
// 解1:最初に思いついたヤツ
def reverse(list:List[Any]):List[Any] = list.reverse
// 解2:地道に作る
def reverse(list:List[Any]):List[Any] = {
	if (list == Nil) Nil
	else reverse(list.tail) ::: List(list.head)
}
// 末尾再帰にしようかとよぎったけれど、次に進む。
P06 (*) Find out whether a list is a palindrome.
回文になっているか?
Example:
scala> isPalindrome(List(1, 2, 3, 2, 1))
res0: Boolean = true
// 解1
def isPalindrome(list:List[Any]):Boolean = {
	if (list == Nil) true
	else if (list.head != list.last) false
	else isPalindrome(list.drop(1).dropRight(1))
}
// 解2:これでOK
def isPalindrome(list:List[Any]):Boolean = list == list.reverse
P07 (**) Flatten a nested list structure.
ネストされたリストを平らにせよ。
Example:
scala> flatten(List(List(1, 1), 2, List(3, List(5, 8))))
res0: List[Any] = List(1, 1, 2, 3, 5, 8)
うーむ、チョット難しくなってきたなぁ〜。
いやいや、Scalaにはそーいうメソッドがすでにあるので簡単に実現できるし、
そういうのを使わないでも実現できるんだけどさ。
ついつい命令型でなく関数型で実装したくなるよね?
安易に命令型で実装してもいいんだけどさ。


というか、これって、LISPで解きたくなるよね。
何もない環境からスタートして、徐々に自分のライブラリを蓄積し、制覇するころには
有益なライブラリが充実している、みたいな。


・・・ゴメン、飽きてきたwww。