Permalink
Browse files

Chapter 2 exercises

  • Loading branch information...
1 parent d142558 commit 5bb1f60280c5841de89d02b3e264dc5d8b71eb71 @rboles committed Feb 26, 2014
Showing with 48 additions and 0 deletions.
  1. +3 −0 curry.scala
  2. +14 −0 fac.scala
  3. +12 −0 is-sorted.scala
  4. +19 −0 partial1.scala
View
@@ -0,0 +1,3 @@
+
+def curry[A, B, C](f: (A, B) => C): A => (B => C) = {
+}
View
@@ -0,0 +1,14 @@
+
+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 formatResult(name: String, n: Int, f: Int => Int) = {
+ val msg = "The %s of %d is %d."
+ msg.format(name, f(n))
+}
View
@@ -0,0 +1,12 @@
+
+// isSorted(List(1,2,4,3), (x: Int, y: Int) => y >= x)
+
+def isSorted[A](l: List[A], cmp: (A, A) => Boolean): Boolean = {
+ def go(i: Int, status: Boolean): Boolean = {
+ if ( !status ) false
+ else if ( i >= l.length - 1 ) true
+ else go(i+1, cmp(l(i), l(i+1)))
+ }
+
+ go(0, true)
+}
View
@@ -0,0 +1,19 @@
+
+// A function that takes a value and a function of 2 arguments
+// it returns a function of 1 argument as a result
+def partial1[A,B,C](a: A, f: (A, B) => C): B => C = {
+
+ def g(b: B): C = f(a, b)
+
+ g
+}
+
+// or more succinctly
+
+def p1[A, B, C](a: A, f: (A, B) => C): B => C = {
+ (b: B) => f(a, b)
+}
+
+// concrete usage
+
+val g = partial1("f", (a: String, b: Boolean) => { if ( a == "f" ) true else false })

0 comments on commit 5bb1f60

Please sign in to comment.