Created
March 26, 2009 20:15
-
-
Save dramsay/86296 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CREDIT: http://on-ruby.blogspot.com/2009/03/author-interview-venkat-subramaniam.html */ | |
/* define method that takes an upperLimit Int and a function literal that accepts | |
* a single Int parameter and returns a Boolean */ | |
def totalSelectValuesInRange(upperLimit: Int, isOKToUse: Int => Boolean) = { | |
/* Create a range by calling to on 1 (in RichInt wrapper for Int) */ | |
val range = 1 to upperLimit | |
/* Fold left on range, starting with 0 - kind of like Ruby's 'inject' */ | |
(0 /: range) { (sum, number) => | |
sum + (if (isOKToUse(number)) number else 0) } | |
} | |
/* _ % 2 == 0 is a function literal - kind of like Ruby lambda, where _ is | |
* a placeholder for the Int that is passed in */ | |
println "Total of even numbers from 1 to 10 is " + | |
totalSelectValuesInRange(10, _ % 2 == 0) | |
println "Total of odd numbers from 1 to 10 is " + | |
totalSelectValuesInRange(10, _ % 2 == 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment