Permalink
Browse files

Curry.scala

  • Loading branch information...
1 parent 945e388 commit 2034b55a4228e3b0ef2e1d830aa36041c47eeefd @tinybyte committed Mar 13, 2011
Showing with 56 additions and 12 deletions.
  1. +35 −0 src/main/scala/usage/Curry.scala
  2. +21 −12 src/test/scala/lang/MaxListSpec.scala
@@ -0,0 +1,35 @@
+package usage
+
+/*
+ Original artical for this: http://www.codecommit.com/blog/scala/function-currying-in-scala
+ It turns out that the best rationale for using currying has to do with general and specialized functions.
+ It would be nice to define a function for the general case,
+ but allow users to specialize the function and then used the specialized version on different data sets.
+ Take the following code as an exampl
+*/
+
+class Curry {
+ def process[A](filter: A => Boolean)(list: List[A]): List[A] = {
+ lazy val recurse = process(filter) _ //the underscore just tells the compiler to treat the suffixed value as a functional, rather than a method to be evaluated.
+
+ list match {
+ case head :: tail => if (filter(head)) {
+ head :: recurse(tail)
+ } else {
+ recurse(tail)
+ }
+
+ case Nil => Nil
+ }
+ }
+
+ val even = (a: Int) => a % 2 == 0
+ val processEvens = process(even) _
+
+ val numbersAsc = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
+ val numbersDesc = 5 :: 4 :: 3 :: 2 :: 1 :: Nil
+
+ processEvens(numbersAsc) // [2, 4]
+ processEvens(numbersDesc) // [4, 2]
+
+}
@@ -4,19 +4,28 @@ import org.scalatest.matchers.ShouldMatchers
import org.scalatest.Spec
class MaxListSpec extends Spec with ShouldMatchers {
- describe("Test MaxList's maxList method") {
- describe("when empty ") {
- it("should throw an Exception"){
- val maxListInstance = new MaxList
- evaluating{maxListInstance.maxList(Nil)} should produce [IllegalArgumentException]
- }
- }
+ describe("Test MaxList's maxList method") {
+ describe("when empty ") {
+ it("should throw an Exception") {
+ val maxListInstance = new MaxList
+ evaluating {
+ maxListInstance.maxList(Nil)
+ } should produce[IllegalArgumentException]
+ }
+ }
- describe("when contains only one element") {
- it("should return that element") {
+ describe("when contains only one element") {
+ it("should return that element") {
val maxListInstance = new MaxList
maxListInstance.maxList(List(1)) should be === 1
- }
- }
- }
+ }
+ }
+
+ describe("when contains more than one elements") {
+ it("should return the max value") {
+ val maxListInstance = new MaxList
+ maxListInstance.maxList(List(13,2,14,5,7)) should be === 14
+ }
+ }
+ }
}

0 comments on commit 2034b55

Please sign in to comment.