코세라 강의 중 괜찮은 예제가 있어서 소개한다.



https://www.coursera.org/learn/progfun1/lecture/JIPKx/lecture-6-2-combinatorial-search-and-for-expressions


scala에서 소수를 구하는 isPrime() 

def isPrime(n: Int): scala.Boolean = (2 until n) forall (n % _ != 0)

println(isPrime(2)) // true
println(isPrime(3)) // true
println(isPrime(4)) // false
println(isPrime(5)) // true
println(isPrime(6)) // false
println(isPrime(7)) // true
println(isPrime(8)) // false
println(isPrime(9)) // false



합산이 소수일때만 더하는 집합 예제이다. 


def isPrime(n: Int): scala.Boolean = (2 until n) forall (n % _ != 0)

val result = (1 until 7) flatMap (i =>
(1 until i) map (j => (i, j))) filter (pair =>
isPrime(pair._1 + pair._2)
)

println(result)


결과는 다음과 같다. 


Vector((2,1), (3,2), (4,1), (4,3), (5,2), (6,1), (6,5))




scalaProduct 예제이다. 

def scalarProduct(left: List[Double], right: List[Double]): Double = (for ((x, y) <- left zip right) yield x * y).sum


결과는 다음과 같다. 


scala> scalarProduct(List(3,4,5), List(2,2,2))

res39: Double = 24.0


Posted by '김용환'
,