Scala与Clojure:函数式编程的魅力与实践
1. Scala中的函数值与多参数列表
在Scala编程中,函数值的使用十分灵活。我们可以通过以下代码来计算价格总和:
println("Total of prices is " +
totalPrices(prices, { price => true }))
//Total of prices is 227
println("Total of prices over 40 is " +
totalPrices(prices, { price => price > 40 }))
//Total of prices over 40 is 127
println("Total of prices under 40 is " +
totalPrices(prices, { price => price < 40 }))
//Total of prices under 40 is 100
这里,我们将集合和函数值作为参数传递给 totalPrices 函数。在Scala里,还支持多参数列表的函数定义,例如:
def totalPrices(
prices : List[Int])(selector : Int => Boolean) = {
prices.foldLeft(0) { (total, price) =>
if (selector(price)) total + price else total
超级会员免费看
订阅专栏 解锁全文
14

被折叠的 条评论
为什么被折叠?



