Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Karol Dziachan
- //task1
- def flatten[A] (xs:List[List[A]]) : List[A] =
- if(xs == Nil) throw new Exception("Empty list")
- else if (xs.length == 1) xs.head
- else xs.head ::: flatten(xs.tail)
- flatten(List(List(1,2,3), List(4,5,6), List(7,8,9))) == List(1,2,3,4,5,6,7,8,9)
- flatten(List(List(), List(1,2,3))) == List(1,2,3)
- flatten(List(List(4,5,6), List())) == List(4,5,6)
- flatten(List())
- //task2
- def count [A] (x: A, xs: List[A]) : Int =
- if(xs == Nil) throw new Exception("empty list")
- else if(xs.tail == Nil)
- if(xs.head == x) 1
- else 0
- else if(xs.head == x) 1+count(x: A, xs.tail)
- else count(x: A, xs.tail)
- count ('a', List('a','l','a')) == 2
- count ('a', List('a','l','a', 'a', 'a', 'm', 'a')) == 5
- count ('a', List('l')) == 0
- count ('a', List('a')) == 1
- count(1, List(1,2,4,1,3,2,1)) == 3
- count ('a', List())
- //task3
- def replicate [A] (x: A, n: Int): List[A] =
- if(n==1) List(x)
- else if(n==0) throw new Exception("Nothing")
- else List(x)::: replicate(x, n-1)
- replicate("la", 3) == List("la", "la", "la")
- replicate("la", 1) == List("la")
- replicate("", 3) == List("", "", "")
- replicate("la", 0)
- replicate("", 0)
- //task4
- def sqrList (xs: List[Int]): List[Int] =
- if(xs == Nil ) throw new Exception("empty list")
- else if(xs.tail != Nil) ((List(xs.head*xs.head) ::: sqrList(xs.tail)))
- else if (xs.head != Nil ) List(xs.head*xs.head)
- else xs
- sqrList(List(1,2, 3, (-4)))
- sqrList(List(1,2,3,4,5))
- sqrList(List((-1), 2, 3, 4, (-5)))
- sqrList(List())
- //task5
- def palindrome[A] (xs: List[A]): Boolean =
- if(xs==Nil) throw new Exception("Empty list")
- else
- xs==xs.reverse
- palindrome(List("a", "l", "a"))
- palindrome(List("A", "l", "a"))
- palindrome(List("k", "a", "j", "a", "k"))
- palindrome(List("k", "a", "r", "o", "l"))
- palindrome(List())
- //task6
- def listLength[A](xs: List[A]): Int =
- if(xs == Nil) throw new Exception ("empty list")
- else if (xs.tail != Nil) 1+listLength(xs.tail)
- else 1
- listLength(List(1,2,3,4,5))
- listLength(List("k", "a", "r", "o", "l"))
- listLength(List("mother"))
- listLength(List("mother", "father"))
- listLength(List())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement