实战 Groovy: 用 curry 过的闭包进行函数式编程
2009-11-19 00:00:00 来源:WEB开发网清单 10 包含 Library 类中的几个闭包,模拟了访问者的用法。action 闭包(与 map 闭包有点相似)把 action 闭包应用于 List 的每个元素。如果某本书被借出,则闭包 displayLoanedBook 显示它;如果某本书未被借出,则闭包 displayAvailableBook 显示它。两者都扮演访问者和相关的动作。用 displayLoanedBook 对 apply 闭包进行 curry 处理,会形成闭包 displayLoanedBooks,它为处理图书集合做好了准备。类似的方案也用来生成可供借阅的图书显示,如清单 10 所示。
清单 10. 修订后的图书馆访问者import fp.*
class Book {
@Property title
@Property author
@Property catalogNumber
@Property onLoan = false
String toString() {
return " Title: ${title}; author: ${author}"
}
}
class Library {
@Property name
@Property stock = [ : ]
def addBook(title, author, catalogNumber) {
def bk = new Book(title : title, author :
author, catalogNumber : catalogNumber)
stock[catalogNumber] = bk
}
def lendBook(catalogNumber) {
stock[catalogNumber].onLoan = true
}
def displayBooksOnLoan() {
println "Library: ${name}"
println "Books on loan"
displayLoanedBooks(stock.values())
}
def displayBooksAvailableForLoan() {
println "Library: ${name}"
println "Books available for loan"
displayAvailableBooks(stock.values())
}
private displayLoanedBook = { bk -> if(bk.onLoan == true)
println bk }
private displayAvailableBook = { bk -> if(bk.onLoan == false)
println bk }
private displayLoanedBooks =
Functor.apply.curry(displayLoanedBook)
private displayAvailableBooks =
Functor.apply.curry(displayAvailableBook)
}
def lib = new Library(name : 'Napier')
lib.addBook('Groovy', 'KenB',
'CS123')
lib.addBook('Java', 'JohnS', 'CS456')
lib.addBook('UML', 'Ken and John',
'CS789')
lib.lendBook('CS123')
lib.displayBooksOnLoan() // Title: Groovy; author: KenB
lib.displayBooksAvailableForLoan() // Title: UML; author: Ken and John
// Title: Java; author: JohnS
- ››Groovy轻松入门
- ››实战:企业使用交换机VLAN路由配置
- ››实战案例分析:高质量软文对网站百度排名的影响
- ››实战经验浅谈网站搬家后的优化工作
- ››实战Active Directory站点部署与管理,Active Dir...
- ››实战操作主机角色转移,Active Directory系列之十...
- ››实战经验:巧用微博推广淘宝网店
- ››实战iPhone GPS定位系统
- ››实战Linux环境配置DBD:Oracle模块
- ››实战DeviceIoControl系列之一:通过API访问设备驱...
- ››实战DeviceIoControl系列之二:获取软盘/硬盘/光盘...
- ››实战DeviceIoControl系列之三:制作磁盘镜像文件
更多精彩
赞助商链接