WEB开发网
开发学院软件开发Java 实战 Groovy: 用 curry 过的闭包进行函数式编程 阅读

实战 Groovy: 用 curry 过的闭包进行函数式编程

 2009-11-19 00:00:00 来源:WEB开发网   
核心提示: 清单 10 包含 Library 类中的几个闭包,模拟了访问者的用法,实战 Groovy: 用 curry 过的闭包进行函数式编程(9),action 闭包(与 map 闭包有点相似)把 action 闭包应用于 List 的每个元素,如果某本书被借出,它为处理图书集合做好了准备,类似的方案也用

清单 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 

上一页  4 5 6 7 8 9 10  下一页

Tags:实战 Groovy curry

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接