Sample Scala Functions

posted in: Scala | 0

Write a function of x power y.

def power (x:Int, n:Int):Int = if ( n==0) 1 else if(n>0 && n%2 == 0) power(x, n/2) * power(x,n/2) else x * power(x, n – 1)

Write QuickSort in Scala

def sort(xs: Array[Int]): Array [Int] = {
if(xs.length <=1) xs else
{

val mid =xs(xs.length/2)
Array.concat(sort(xs filter(mid>)),
xs filter (mid ==),
sort(xs filter (mid <)))
}
}

Write (GCD) greatest  common  divisor  of  two numbers.
def gcd(a: Int, b: Int): Int =
if (b == 0) a
else
gcd(b, a % b)

Factorial of a number:

def fact(n:Int):Int = if (n==0) 1 else n*fact(n-1)

Write square root function:

def abs(x:Double) = if (x < 0) -x else x
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess -x)/x <0.001

def improve(guess: Double, x: Double) =(guess + x / guess) / 2
def sqrtIter(guess: Double, x: Double): Double ={
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)}
def sqrt(x: Double) = sqrtIter(1.0, x)