Skip to content

Instantly share code, notes, and snippets.

@dramsay
Created March 26, 2009 20:15
Show Gist options
  • Save dramsay/86296 to your computer and use it in GitHub Desktop.
Save dramsay/86296 to your computer and use it in GitHub Desktop.
/* 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