2015年5月17日日曜日

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

Exercise 3.16 各要素に1ずつたして整数のリストを返す関数を記述せよ

def add1(as:List[Int]):List[Int]=
 as match {
  case Nil => Nil
  case Cons(x,xs)=> Cons(x+1,add1(xs))
}

def add1f(as:List[Int]):List[Int]=
  foldRight(as:List[Int],Nil:List[Int])((a:Int,b:List[Int])=>Cons(a+1,b))


Exercise 3.17 List[Double]の各値をStringに変換する関数を記述せよ

def toStringD(as:List[Double]):List[String]=
 foldRight(as:List[Double],Nil:List[String])((a:Double,b:List[String])=>Cons(a.toString,b))

Exercise 3.18 リストの各要素を変更し、かつリストの構造をそのまま保つ総称関数mapを記述せよ。
def map[A,B}(as:List[A])(f:A=>B):List[B]=
 foldRight(as:List[A],Nil:List[B])((a:A,b:List[B])=>Cons(f(a),b))

Exercise 3.19 与えられた述語条件が満たされるまでリストから要素を削除するfilter関数を記述せよ。

def filter[A](as:List[A])(f:A=>Boolean):List[A]=
 foldRight(as:List[A],Nil:List[A])((a:A,b:List[A])=>(if (f(a)) Cons(a,b) else b ))

0 件のコメント:

コメントを投稿