Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.annotation.tailrec
- def take[A](n: Int, xs: List[A]): List[A] = {
- xs match {
- case h :: t if n > 0 => h :: take(n - 1, t)
- case _ => Nil
- }
- }
- assert(take(2, List(1, 2, 3, 5, 6)) == List(1, 2))
- assert(take(20, Nil) == Nil)
- assert(take(2, List(1, 2)) == List(1, 2))
- assert(take(0, List(1, 2, 3, 5, 6)) == Nil)
- assert(take(-2, List(1, 2, 3, 5, 6)) == Nil)
- assert(take(8, List(1, 2, 3, 5, 6)) == List(1, 2, 3, 5, 6))
- def drop[A](n: Int, xs: List[A]): List[A] = {
- xs match {
- case _ :: t if n > 0 => drop(n - 1, t)
- case _ => xs
- }
- }
- assert(drop(2, List(1, 2, 3, 5, 6)) == List(3, 5, 6))
- assert(drop(0, List(1, 2, 3)) == List(1, 2, 3))
- assert(drop(3, List(1, 2, 3)) == Nil)
- assert(drop(20, Nil) == Nil)
- assert(drop(-2, List(1, 2, 3, 5, 6)) == List(1, 2, 3, 5, 6))
- assert(drop(8, List(1, 2, 3, 5, 6)) == Nil)
- def reverse[A](xs: List[A]): List[A] = {
- def r[A](xs: List[A], acc: List[A]): List[A] = {
- xs match {
- case h :: t => r(t, h :: acc)
- case _ => acc
- }
- }
- r(xs, Nil)
- }
- assert(reverse(List("Ala", "ma", "kota")) == List("kota", "ma", "Ala"))
- assert(reverse(Nil) == Nil)
- def initSegment[A](xs: List[A], ys: List[A]): Boolean = {
- (xs, ys) match {
- case (Nil, _) => true
- case (x_h :: x_t, y_h :: y_t) if x_h == y_h => initSegment(x_t, y_t)
- case _ => false
- }
- }
- assert(initSegment(List(1, 2), List(1, 2, 3, 4)))
- assert(initSegment(Nil, List(1)))
- assert(initSegment(Nil, Nil))
- assert(initSegment(List(1, 2), List(1, 2)))
- assert(!initSegment(List(1, 2, 3), List(1, 2)))
- assert(!initSegment(List(1, 2), List(1, 3, 4, 5)))
- def replicate(xs: List[Int]): List[Int] = {
- def repNTimes(xs: List[Int], n: Int): List[Int] = {
- (xs,n) match{
- case (h::t,_) if n>0 => h:: repNTimes(xs,n-1)
- case (h1::h2::t,_) => repNTimes(h2::t,h2)
- case _ => Nil
- }
- }
- if(xs==Nil)
- Nil
- else
- repNTimes(xs,xs.head)
- }
- assert(replicate(List(1,0,4,-2,3))==List(1, 4, 4, 4, 4, 3, 3, 3))
- assert(replicate(List(0,-1,0,-2))==Nil)
- assert(replicate(List(0,-1,0,1,-2))==List(1))
- assert(replicate(List(2,1,0,0,-1,-15,2))==List(2,2,1,2,2))
- def newtonRaphson(a: Double, eps: Double): Double = {
- 2.0
- }
- def root3(a:Double) : Double ={
- @tailrec
- def root3(a:Double,x:Double,eps:Double):Double = {
- if (Math.abs(Math.pow(x,3)-a) <= eps * Math.abs(a))
- x
- else
- root3(a,x+(a/(x*x)-x)/3,eps)
- }
- if (a>1)
- root3(a,a/3,10e-15)
- else
- root3(a,a,10e-15)
- }
- assert(root3(-8.0) == -2.0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement