Advertisement
Guest User

foldLeft using foldRight expansion

a guest
Sep 29th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.32 KB | None | 0 0
  1. def foldRight[A,B](l: List[A], z: B)(f: (A, B) => B): B =
  2.   l match {
  3.     case Nil => z
  4.     case Cons(a, as) => f(a, foldRight(as, z)(f))
  5.   }
  6.  
  7. def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B =
  8.   foldRight(l, (b:B) => b)((a,g) => b => g(f(b,a)))(z)
  9.  
  10.  
  11.  
  12. foldLeft(List(1,2), 0)(_ + _)
  13.  
  14. // A = Int
  15. // B = (Int => Int)
  16.  
  17. // foldLeft rewritten in terms of foldRight
  18. foldRight(List(1,2), (i:Int) => i)((x:Int, g: Int => Int) => (i:Int) => g(f(i,x)))(0)
  19.  
  20. //---Recurse---
  21.  
  22. // x = 1
  23. ((j:Int) => g(f(j,1)))(0)
  24.  
  25. // g = foldRight(List(2), (i:Int) => i)((x:Int, g: Int => Int) => (i:Int) => g(f(i,x)))
  26. ((j:Int) => foldRight(List(2), (i:Int) => i)((x:Int, g: Int => Int) => (i:Int) => g(f(i,x)))(f(j,1)))(0)
  27.  
  28. //---Recurse---
  29.  
  30. // x = 2
  31. ((j:Int) => ((k:Int) => g(f(k,2)))(f(j,1)))(0)
  32.  
  33. //g = foldRight(Nil, (i:Int) => i)((x:Int, g: Int => Int) => (i:Int) => g(f(i,x)))
  34. ((j:Int) => ((k:Int) => foldRight(Nil, (i:Int) => i)((x:Int, g: Int => Int) => (i:Int) => g(f(i,x)))(f(k,2)))(f(i,1)))(0)
  35.  
  36. //---Recurse---
  37.  
  38. // z = (i:Int) => i
  39. ((j:Int) => ((k:Int) => ((i:Int) => i)(f(k,2)))(f(j,1)))(0)
  40.  
  41. //---Apply and Simplify---
  42.  
  43. // j = 0
  44. ((k:Int) => ((i:Int) => i)(f(k,2)))(f(0,1))
  45.  
  46. // k = f(0,1)
  47. ((i:Int) => i)(f(f(0,1),2))
  48.  
  49. // i = f(f(0,1),2)
  50. f(f(0,1),2)
  51.  
  52. // f = (_ + _)
  53. f((0 + 1), 2)
  54.  
  55. // f = (_ + _)
  56. ((0 + 1) + 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement