Drkcore

29 09 2011 Scala Tweet

Ninety-Nine Scala Problems (P31)

S-99を解く。Int型にisPrimeっていう素数かどうかを判定するメソッドを組み込む問題。

implicit defをつかえばいい。

ProductName Scalaスケーラブルプログラミング第2版
Martin Odersky
インプレスジャパン / 4830円 ( 2011-09-27 )


class IntWrapper(n:Int){
 def isPrime():Boolean = (n != 1) &&
(List.range(2,math.sqrt(n).toInt+1) forall (i => n % i != 0))
}

implicit def int2IntWrapper(n:Int) = new IntWrapper(n)

for (n <- 1 to 10)
 println(n + ": " + n.isPrime)

ところで、解答見たらstream使った例が載ってたんだけどこれ動かないんだけどナニが悪いの?

/Users/kzfm/scala/p31.scala:3: error: not found: value primes
    (start > 1) && (primes takeWhile { _ <= Math.sqrt(start) } forall { start % _ != 0 })
                    ^
/Users/kzfm/scala/p31.scala:7: error: value isPrime is not a member of Int
  val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })

コード

class S99Int(val start: Int) {
  def isPrime: Boolean =
    (start > 1) && (primes takeWhile { _ <= Math.sqrt(start) } forall { start % _ != 0 })
}

object S99Int {
  val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })
}

About

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

Tag

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

Ad

© kzfm 2003-2021