Created
May 13, 2011 16:06
-
-
Save pokutuna/970810 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//http://www29.atwiki.jp/tmiya/pages/55.html | |
import scala.annotation.tailrec | |
object Exercises { | |
def succ(n:Int) = n + 1 | |
def pred(n:Int) = n - 1 | |
@tailrec | |
def add(x:Int, y:Int):Int = | |
if (y == 0) x else add(succ(x), pred(y)) | |
def sum(x:List[Int]):Int = x match { | |
case Nil => 0 | |
case head :: tail => add(head, sum(tail)) | |
} | |
def length[A](x:List[A]):Int = x match { | |
case Nil => 0 | |
case head :: tail => 1 + length(tail) | |
} | |
def map[A,B](x:List[A], f:A => B):List[B] = x match { | |
case Nil => Nil | |
case head :: tail => f(head) :: map(tail, f) | |
} | |
def filter[A](x:List[A], f:A => Boolean):List[A] = x match { | |
case Nil => Nil | |
case head :: tail => | |
if(f(head) == true) head :: filter(tail,f) else filter(tail,f) | |
} | |
def append[A](x:List[A], y:List[A]):List[A] = x match { | |
case Nil => y | |
case head :: tail => head :: append(tail, y) | |
} | |
def concat[A](x:List[List[A]]):List[A] = x match { | |
case Nil => Nil | |
case head :: tail => append(head, concat(tail)) | |
} | |
def concatMap[A,B](x:List[A], f:A => List[B]):List[B] = concat(map(x, f)) | |
def maximum(x:List[Int]):Int = x match { | |
case Nil => throw new RuntimeException | |
case head :: Nil => head | |
case head :: tail => if(head > maximum(tail)) head else maximum(tail) | |
} | |
def reverse[A](x:List[A]):List[A] = { | |
def reverseRec(result:List[A], xl:List[A]):List[A] = xl match { | |
case Nil => result | |
case head :: tail => reverseRec(head :: result, tail) | |
} | |
reverseRec(Nil, x) | |
} | |
def main(args: Array[String]) = { | |
println(add(5, 10)) | |
println(sum(1 to 10 toList)) | |
println(length(1 to 100 by 3 toList)) | |
println(map(List(1,2,3,4,5), { (n:Int) => n *2})) | |
println(filter(1 to 20 by 3 toList, {(n:Int) => n%2 == 0})) | |
println(append(1 to 20 by 3 toList, 5 to 10 by 2 toList)) | |
println(concat(List(List(1,2,3), List(2,4,6), List(8,10,12)))) | |
println(concatMap(1 to 3 toList, {(n:Int) => n :: n :: n :: Nil})) | |
println(maximum(List(10,3,5,12,19,4,2))) | |
println(reverse(List(1,2,3,4,5))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment