Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object h {
- def main(args: Array[String]) {
- //println(factorial(6))
- //println(fib(6))
- //println(findFirst(Array(4,7,9,6,2), (x:Int)=>x==7))
- //println(isSorted(Array(1,2,3,5,4), (x:Int, y:Int) => x<y))
- }
- def factorial(n: Int): Int = {
- @annotation.tailrec
- def go(n: Int, acc: Int): Int =
- if (n <= 0) acc
- else go(n - 1, n * acc)
- go(n, 1)
- }
- def fib(n: Int): Int = {
- @annotation.tailrec
- def go(n: Int, a: Int, b: Int): Int =
- if (n <= 0) b
- else go(n - 1, b, b + a)
- go(n, 0, 1)
- }
- def findFirst[A](a: Array[A], p: (A) => Boolean): Int = {
- @annotation.tailrec
- def loop(n: Int): Int =
- if (n >= a.length) -1
- else if (p(a(n))) n
- else (loop(n + 1))
- loop(0)
- }
- def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
- @annotation.tailrec
- def go(n: Int): Boolean =
- if (n == as.length - 1) true
- else if (ordered(as(n), as(n + 1))) go(n + 1)
- else false
- go(0)
- }
- def partial1[A,B,C](a: A, f: (A,B) => C): B => C =
- (b: B) => f(a, b)
- }
- def curry[A,B,C](f: (A, B) => C): A => (B => C){
- a=>b=>f(a,b)
- }
- def uncurry[A,B,C](f: A => B => C): (A, B) => C{
- f(a)(b)=f(a,b) /*apply parameter a to the function f, then take the resulting function and apply the parameter b to it*/
- }
- def compose[A,B,C](f: B => C, g: A => B): A => C{
- a=>f(g(a))
- }
- }
- def curry[A,B,C](f: (A, B) => C): A => (B => C){
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement