-
-
Save tamizhgeek/d6244432b1035ffad928 to your computer and use it in GitHub Desktop.
package assignments | |
object ListUtils { | |
def findLast(list : List[Int]) :Int = { | |
list match { | |
case a :: Nil => a | |
case a :: b => findLast(b) | |
} | |
} | |
def lenCustom(list: List[Int]) : Int = { | |
list match { | |
case (Nil) => 0 | |
case (a :: Nil) => 1 | |
case (a :: b) => 1 + lenCustom(b) | |
} | |
} | |
def penultimate(list: List[Int]) : Int = { | |
list match { | |
case (a :: b :: Nil) => a | |
case (a :: b) => penultimate(b) | |
} | |
} | |
def reverse(list: List[Int]) : List[Int] = { | |
def collect(list: List[Int], newList : List[Int]) : List[Int] = { | |
list match { | |
case (Nil) => newList | |
case a :: b => collect(b, a :: newList) | |
} | |
} | |
collect(list, List()) | |
} | |
def removeDuplicates(list : List[Int]) : List[Int] = { | |
list match { | |
case Nil => Nil | |
case a :: Nil => a :: Nil | |
case (a1 :: a2 :: b) => { | |
if(a1 == a2) | |
removeDuplicates(a1 :: b) | |
else | |
a1 :: removeDuplicates( a2 :: b) | |
} | |
} | |
} | |
def drop(interval : Int, list : List[Int]) : List[Int] = { | |
def collect(currentIdx : Int, newList : List[Int]) : List[Int] = { | |
if(lenCustom(list) == currentIdx) return newList | |
if(((currentIdx + 1) % interval) == 0) collect(currentIdx + 1, newList) | |
else collect(currentIdx + 1, newList :+ list.apply(currentIdx)) | |
} | |
collect(0, List()) | |
} | |
def slice(start : Int, end : Int, list : List[Int]) : List[Int] = { | |
def collect(currentIdx : Int, newList : List[Int]) : List[Int] = { | |
currentIdx match { | |
case a if(a < start) => collect(a + 1, newList) | |
case a if(a >= start && a < end) => collect(a + 1, newList :+ list.apply(a)) | |
case a => newList | |
} | |
} | |
collect(0, List()) | |
} | |
} |
Line 34, 47, 60 - Using Any
invalidates any type checks that compiler can give you. We refrain from using Any
unless totally required. If the intentions were to support all types of list, it is better to use generics (we'll cover it soon in the forth coming sessions).
Line 50 - Could we've used a simple if-else for this? Pattern matching seems a bit of an overkill here.
Line 51, 54, 63-65: Would throw a compiler warning since the type are erased when converting to byte code. We can avoid the ': Int' part safely since currentIdx
is of type Int
.
Ashwanth - Nailed. Pattern matching can be deceptive. You need to be clear when to use it and when to use if-else. And, secondly help the Type checker by not giving Any :)
L#51, 54 cases can be converted to Case 0 => do_something and Case _ => do_something_else
Incorporated the comment changes. But i have a lot of questions. Will come and bug either of you to get more clarity.
List reverse complexity seems high. Can you take another stab at it?