Created
March 2, 2015 13:38
-
-
Save dimitrisli/1f6663ae5a4ab66dd155 to your computer and use it in GitHub Desktop.
Scala 99 Problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//P01 | |
def last(ls: List[Int]): Int = ls match { | |
case le::Nil => le | |
case _::tail => last(tail) | |
case _ => throw new IllegalArgumentException | |
} | |
//P02 | |
def penultimate(ls: List[Int]): Int = ls match { | |
case pmate::_::Nil => pmate | |
case _::tail => penultimate(tail) | |
case _ => throw new IllegalArgumentException | |
} | |
//P03 | |
def nth(i:Int, l:List[Int]):Int = (i,l) match { | |
case(0,h::_) => h | |
case(k,_::tail) if k>=0 => nth(k-1,tail) | |
case _ => throw new IllegalArgumentException | |
} | |
//P04 | |
def length(l:List[Int]) = { | |
def lengthAcc(l:List[Int],acc:Int):Int = l match { | |
case Nil => acc | |
case _::tail => lengthAcc(tail,acc+1) | |
} | |
lengthAcc(l,0) | |
} | |
def lengthFunc(l:List[Int]):Int = l.foldLeft(0){(acc,_)=>acc+1} | |
//P05 | |
def reverse(l:List[Int]):List[Int]= { | |
def reverseAcc(l:List[Int],acc:List[Int]):List[Int] = l match { | |
case Nil => acc | |
case h::tail => reverseAcc(tail, h::acc) | |
} | |
reverseAcc(l,List()) | |
} | |
def reverseFunc(l:List[Int]):List[Int] = l.foldLeft(List[Int]()){ (acc, v) => v::acc} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment