2015年5月31日日曜日

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

Exercise 6.5 mapを使ってdoubleを実装し直せ

val rng = new scala.util.Random

trait RNG{
def nextInt:(Int,RNG)
}

case class SimpleRNG(seed: Long) extends RNG {
 def nextInt:(Int,RNG) = {
   val newSeed =(seed * 0x5DEECE66DL+0xBL) & 0xFFFFFFFFFFFFL
   val nextRNG= SimpleRNG(newSeed)
   val n = (newSeed >>>16).toInt
    (n,nextRNG)
 }
}

def nonNegativeInt(rng: RNG): (Int, RNG) = {
  val (i, r) = rng.nextInt
  (if (i < 0) -(i + 1) else i, r)
}

type Rand[+A]=RNG=>(A,RNG)

def map [A,B](s:Rand[A])(f:A=>B):Rand[B]=
 rng=>{
 val (a,rng2) = s(rng)
  (f(a),rng2)
}

def _double(rng:RNG):Rand[Double] =
 map (nonNegativeInt)(_/(Int.MaxValue.toDouble+1))

val (a,rng2) = _double(rng)(rng)で確認

0 件のコメント:

コメントを投稿