Advertisement
plantbae

FP ref

Jan 22nd, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.50 KB | None | 0 0
  1. object h {
  2.   def main(args: Array[String]) {
  3.     //println(factorial(6))
  4.     //println(fib(6))
  5.     //println(findFirst(Array(4,7,9,6,2), (x:Int)=>x==7))
  6.     //println(isSorted(Array(1,2,3,5,4), (x:Int, y:Int) => x<y))
  7.   }
  8.  
  9.   def factorial(n: Int): Int = {
  10.     @annotation.tailrec
  11.     def go(n: Int, acc: Int): Int =
  12.       if (n <= 0) acc
  13.       else go(n - 1, n * acc)
  14.     go(n, 1)
  15.   }
  16.  
  17.   def fib(n: Int): Int = {
  18.     @annotation.tailrec
  19.     def go(n: Int, a: Int, b: Int): Int =
  20.       if (n <= 0) b
  21.       else go(n - 1, b, b + a)
  22.     go(n, 0, 1)
  23.   }
  24.  
  25.   def findFirst[A](a: Array[A], p: (A) => Boolean): Int = {
  26.     @annotation.tailrec
  27.     def loop(n: Int): Int =
  28.       if (n >= a.length) -1
  29.       else if (p(a(n))) n
  30.       else (loop(n + 1))
  31.     loop(0)
  32.   }
  33.  
  34.   def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
  35.     @annotation.tailrec
  36.     def go(n: Int): Boolean =
  37.       if (n == as.length - 1) true
  38.       else if (ordered(as(n), as(n + 1))) go(n + 1)
  39.       else false
  40.     go(0)
  41.   }
  42.  
  43.   def partial1[A,B,C](a: A, f: (A,B) => C): B => C =
  44.         (b: B) => f(a, b)
  45.   }
  46.  
  47.   def curry[A,B,C](f: (A, B) => C): A => (B => C){
  48.     a=>b=>f(a,b)
  49.   }
  50.  
  51.     def uncurry[A,B,C](f: A => B => C): (A, B) => C{
  52.     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*/
  53.   }
  54.  
  55.     def compose[A,B,C](f: B => C, g: A => B): A => C{
  56.     a=>f(g(a))
  57.   }
  58.  
  59. }
  60.  
  61.  
  62. def curry[A,B,C](f: (A, B) => C): A => (B => C){
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement