Skip to content

Instantly share code, notes, and snippets.

@stew
Created August 31, 2012 02:53
Show Gist options
  • Save stew/3548331 to your computer and use it in GitHub Desktop.
Save stew/3548331 to your computer and use it in GitHub Desktop.
example of currying
// you have items
case class Item(name: String, price: Double)
// their prices can be adjusted. To adjust a price, pass a function
// which takes the old price, and gives a new price
def adjustPrice(i: Item, discountFunction: Double => Double) = {
// return a new copy with the price changed
i.copy(price = discountFunction(i.price))
}
def absoluteDiscount(amount: Double)(oldPrice: Double) = oldPrice - amount
def fractionalDiscount(percent: Double)(oldPrice: Double) = oldPrice * percent
def setNewPrice(newPrice: Double)(oldPrice: Double) = newPrice
def setToZero(oldPrice: Double) = 0
val items = List(Item("one hundred", 100d),
Item("fifty", 50d))
val discounted10 = items.map { item => adjustPrice(item, absoluteDiscount(10d)) }
val fiftyPercent = items.map { item => adjustPrice(item, fractionalDiscount(.5)) }
val all20 = items.map { item => adjustPrice(item, setNewPrice(20)) }
val everythingIsFree = items.map { item => adjustPrice(item, setToZero) }
println( discounted10)
println( fiftyPercent)
println( all20)
println( everythingIsFree)
// curry the adjust price function so that it retuns a new function
// which modifies a particular item
val groovy = Item("groovy", 1000)
val adjustGroovy : (Double => Double) => Item = adjustPrice(groovy, _)
println(adjustGroovy(absoluteDiscount(10)))
println(adjustGroovy(fractionalDiscount(.30)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment