2015年5月17日日曜日

scala関数型デザイン&プログラミング P56

 Exercise 3.25 LeafとBranchの数を数えるsize関数を記述せよ
 def size[A](t:Tree[A]):Int=
  t match {
  case Leaf(a) => 1
  case Branch(lt,rt) => 1+size(lt)+size(rt)
  }

Exercise 3.26 Tree[Int]の最大の要素を]返すmaximum関数を記述せよ。
def maximum(t:Tree[Int]):Int=
 t match {
  case Leaf(a) =>a
  case Branch(lt,rt) => maximum(lt) max maximum(rt)
 }

 Exercise 3.27 2分木のルートから任意のLeafまでの最長パスを返すdepth関数を記述せよ
 def depth[A](t:Tree[A]):Int=
  t match {
   case Leaf(_) => 0
   case Branch(lt,rt) => 1+(depth(lt) max depth(rt))
  }

  Exercise 3.28 2分木の各要素を特定の関数を使って変換するmap関数を記述せよ。
def map[A,B](t:Tree[A])(f:A=>B):Tree[B]=
 t match {
  case Leaf(a)=>Leaf(f(a))
  case Branch(lt,rt)=>Branch(map(lt)(f),map(rt)(f))
 }

0 件のコメント:

コメントを投稿