0% found this document useful (0 votes)
17 views2 pages

Solution Scala

Uploaded by

кана л
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views2 pages

Solution Scala

Uploaded by

кана л
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import scala.annotation.

tailrec;
import scala.math._

// task 1
val fib: Int => Int = {
case 0 => 0
case 1 => 1
case n => fib(n - 2) + fib(n - 1)
}

val fibTail = (n: Int) => {


@tailrec
def aux(n: Int, a: Int, b: Int): Int = {
n match {
case 0 => a
case _ => aux(n - 1, b, a + b)
}
}
aux(n, 0, 1)
}

fib(42)
fibTail(42)

// task 2
val root3Func = (a: Double) => {
val precision = 1e-15
@tailrec
def aux(x: Double): Double = {
if (abs(pow(x, 3) - a) <= precision * abs(a)) x
else aux(x + (a / pow(x, 2) - x) / 3)
}
aux(if(a > 1) a / 3 else a)
}

def root3(a: Double): Double = {


val precision = 1e-15
@tailrec
def aux(x: Double): Double = {
if (abs(pow(x, 3) - a) <= precision * abs(a)) x
else aux(x + (a / pow(x, 2) - x) / 3)
}
aux(if (a > 1) a / 3 else a)
}

root3Func(-216)
root3(-216)

// task 3
val List(_, _, x, _, _) = List(-2, -1, 0, 1, 2)
val List((_, _), (y, _)) = List((1, 2), (0, 1))

// task 4
@tailrec
def initSegment[A](xs: List[A], ys: List[A]): Boolean = {
(xs, ys) match {
case (Nil, _) => true
case (_, Nil) => false
case (xHead :: xTail, yHead :: yTail) =>
if (xHead == yHead) {
initSegment(xTail, yTail)
} else false
}
}

initSegment(List(1, 2, 3), List(1, 2, 3, 4, 5))

// task 5
def replaceNth[A](list: List[A], n: Int, x: A): List[A] = {
(list, n) match {
case (Nil, _) => Nil
case (_ :: tail, 0) => x :: tail
case (head :: tail, _) => head :: replaceNth(tail, n - 1, x)
}
}

replaceNth(List('o','l','a', 'm','a', 'k','o','t','a'), 1, 's')

You might also like