Skip to content

Commit

Permalink
Curry.scala
Browse files Browse the repository at this point in the history
  • Loading branch information
tinybyte committed Mar 13, 2011
1 parent 945e388 commit 2034b55
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 12 deletions.
35 changes: 35 additions & 0 deletions src/main/scala/usage/Curry.scala
Original file line number Diff line number Diff line change
@@ -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]

}
33 changes: 21 additions & 12 deletions src/test/scala/lang/MaxListSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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.