Drkcore

23 09 2011 Scala Tweet

Ninety-Nine Scala Problems (P01 - P10)

S-99を解く。Scalaは基本は関数型で考えて、どうしようもないときにはOOPに逃げられるのがいいですね。

ProductName Scalaスケーラブルプログラミング[コンセプト&コーディング] (Programming in Scala)
Martin Odersky
インプレスジャパン / 4830円 ( 2009-08-21 )


//1
def last[A](ls:List[A]): A = ls.last

println("s1: " + last(List(1, 1, 2, 3, 5, 8)))

//2
def penultimate[A](ls:List[A]): A = ls.init.last

println("s2: " + penultimate(List(1, 1, 2, 3, 5, 8)))

//3
def nth[A](n:Int, ls:List[A]): A = if (n == 0) ls.head else nth(n-1,ls.tail)

println("s3: " + nth(2, List(1, 1, 2, 3, 5, 8)))

//4
def length[A](ls:List[A]): Int = ls.length

println("s4: "+ length(List(1, 1, 2, 3, 5, 8)))

//5
def reverse[A](ls:List[A]): List[A] = {
  def reverse2[A](ls:List[A],ls2:List[A]): List[A] = ls match {
      case Nil => ls2 
      case (head::tail) => reverse2(tail,head::ls2)
    }
  reverse2(ls,Nil)
}
println("s5: " + reverse(List(1, 1, 2, 3, 5, 8)))

//6
def isPalindrome[A](ls:List[A]): Boolean = ls == reverse(ls)

println("s6: " +  isPalindrome(List(1, 2, 3, 2, 1)))

//7
def flatten(ls: List[Any]): List[Any] = ls flatMap {
  case ms:List[_] => flatten(ms)
  case e => List(e)
}

println("s7: " + flatten(List(List(1, 1), 2, List(3, List(5, 8)))))

//8
def compress[A](ls:List[A]): List[A] = ls match {
  case Nil    => ls
  case head::tail => head::compress(tail.dropWhile(_ == head))
}

println("s8: " + compress(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

//9
def pack[A](ls:List[A]): List[List[A]] = ls match {
  case Nil => Nil
  case head::tail => ls.takeWhile(_ == head) :: pack(tail.dropWhile(_ == head))
}

println("s9: " + pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

//10
def encode[A](ls: List[A]): List[(Int, A)] = pack(ls) map {e => (e.length, e.head)}

println("s10: " + encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)))

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021