”函数柯里化”是指将多变量函数拆解为单变量的多个函数的调用, 可以从高元函数动态地生成大量低元的函数。可以看成一个强大的函数工厂,结合函数式编程,可以叠加出很BT的能力。下面给出了一个示例,说明如何使用 Currying 用一行代码计算任意指数的多项式的和; 以及使用 Currying 实现一个简单的文件处理框架。
注意到, Currying 的过程中,参数的顺序是有讲究的。一般, 函数参数建议放在前面,按照想要调用的顺序; 数据参数放在后面。
package scalastudy.basic import scala.util.matching.Regex import scala.math.pow import scalastudy.utils.{PathConstants, DefaultFileUtil} /** * Created by lovesqcc on 16-4-16. */ object CurryDemo extends App { launch() def launch(): Unit = { val listNum = 10 val alist = (1 to listNum).toList for (i <- 1 to 3) { val listPolySum = polynomialSum(i)(_) println(listPolySum(alist)) } val filename = PathConstants.scalaSrcPath + "/basic/CurryDemo.scala" val fileContentHandler = handleFile(DefaultFileUtil.readFile)(_) val findInFileFunc = fileContentHandler(findInFile)(_) println(findInFileFunc(filename)) val countInFileFunc = fileContentHandler(countInFile)(_) println("Non Empty Lines: " + countInFileFunc(filename)) } /* * calc 1^m + 2^m + ... + n^m */ def polynomialSum(m: Int)(list: List[Int]): Long = { return list.map(pow(_,m)).sum.asInstanceOf[Long]; } def handleFile(filePathHandler:(String) => String) (fileContentHandler: (String) => Any) (filepath: String): Any = { return fileContentHandler(filePathHandler(filepath)) } def findInFile(text:String):Any = { val patt = "f\\w+".r return patt.findAllIn(text).toList } def countInFile(text:String):Any = { return text.split("\n").toList.filter(s => ! s.matches("^\\s*$")).length } }
package scalastudy.utils /** * Created by lovesqcc on 16-4-16. */ object PathConstants { val projPath = System.getProperty("user.dir") val scalaSrcPath = projPath + "/src/main/java/scalastudy" }
时间: 2024-10-09 15:16:01