`

scala - function and closures

阅读更多

In this example, we are going to examine the function and closures and here is the outline.

 

 

1. Function

1.1. one thing about Scala is that 

1.2 first class function

1.3 function can be short-forms

1.4 placeholder syntax

2. closure

2.1.  closure in simple form 

3. function call in special form 

3.1 repeated parameters

3.2 Default parameter values 

4. tail recursion 

4.1 an interest note on the tail-recursion limit

 

 

// function_closures.scala

// scala functions and closures in example 

// 1. Function
//
// 1.1. one thing about Scala is that 
//   one strong suite about scala is that you can define local function for Scala

import scala.io.Source

object LongLines {
  def processFile(fileName : String, width : Int) = {
    
    // local function
    def processLine(line : String) = {
      if (line.length > width) println(fileName + ": " + line)
    }
    
    for (line <- Source.fromFile(fileName).getLines) 
      processLine(line)
  }
  
}
// runner 
LongLines.processFile("C:\\dev\\workspace\\scala-train\\src\\functionsAndClosures\\function_closures.scala", 6)

// 1.2 first class function
// function as the first class type means 
//  1). you can create a function literal, which when is compiled into a class that when instantiated at runtime is a function value
//  2). you can pass around the function value around
(x :Int) => x + 1

var increase = (x :Int) => x + 1


val someNumbers = List(-11, -10, -5, 0, 5, 10)

someNumbers.foreach((x :Int) => println(x))

// 1.3 function can be short-forms
// longer form 
someNumbers.filter((x :Int) => x > 0)
// short form
someNumbers.filter(x => x > 0)

//1.4 placeholder syntax
// why do we need 'x', since we barely need that variable name, we can ignore the
// 'x' and the parameter part , and just use following functional body literal
someNumbers.filter(_ > 0)

val f = ( _ : Int) + (_ : Int) 

f(5, 10)

//1.4 partially function

def sum(a :Int, b : Int, c :Int) = a + b  + c

// you can use '_' to create a partially apply function by which you supply none of the required arguments

val a = sum _
a (1 ,2, 3 )
// above is interchanable to the following
a.apply(1, 2, 3)


val b = sum (1, _ :Int, 3)

b(2)

someNumbers.foreach(println _)

// if you are writing a partially function in which you leave off all the parameters, such as println _, or sum _, you can express more concisely by leaving 
// off the underscore if a function is required at that point in the code 
someNumbers.foreach(println)

//NOTE: you cannot do that if data is required... 



//2. closure
// closure is the abilty from within a scope (a local functional literal) which refers to some free local variable, and because of that 
// the lifetime of the freevar has been extended with the local/anonymous function


// 2.1.  closure in simple form 

var more = 1

val addMore = (x : Int) => x + more 

addMore(1)
more = 9999

addMore(10)

// 
def makeIncreaser(more : Int) = (x: Int) => x + more  

val increaser1 = makeIncreaser(1)

val increaser2 = makeIncreaser(2) 

// each time makeIncreaser is called, a new closure is created 
increaser1 == increaser2

// 3. function call in special form 
// 3.1 repeated parameters
def echo(args : String*) = for (arg <- args) println(arg)



echo()
echo("one")
// actually Array[String] will be passed in to the function below  
echo("hello", "world")

// how do we unpack a array, list and pass that as repeated parameters? 
// the key lies in "_*" 
val arr = Array("what's", "is", "up")

echo(arr : _*)


// 3.2 Default parameter values 
// you can pass in default parameter values
def printTime(out : java.io.PrintStream = Console.out) = out.println("Time = " +  System.currentTimeMillis())

// you can call function with default argument values
// with the named arguments (which is called keyword argument in Python) 
def printTime2(out : java.io.PrintStream = Console.out, divisor: Int = 1) = out.println("Time = " +  System.currentTimeMillis() / divisor)

printTime2(divisor = 2)


// 3. tail recursion 
// tail recursion is an  optimization that is performed by the compiler, it just jump back to the beginning of the function 
// with parameter values replaced..

// a non-tail recursive function
def boom(x :Int) : Int = 
  if (x == 0) throw new Exception("boom!")
  else boom(x - 1 ) + 1
// check the stack   
boom(2)  

// a tail recursive one 
def boom(x :Int) : Int = 
  if (x == 0) throw new Exception("boom!")
  else boom(x - 1 )

boom(10)
  
// 3.1 an interest note on the tail-recursion limit
//
// this do not do tail-recursion
def isEven(x : Int) : Boolean = if (x == 0) true else isOdd(x - 1)
def isOdd(x : Int) : Boolean = if (x == 0) false else isEven(x - 1)

isEven(9)

val funValue = nestedFun _
def nestedFun (x : Int) {
  if (x != 0) { println(x); funValue(x - 1)}
}

funValue(3)

 

分享到:
评论

相关推荐

    scala-parser-combinators_2.12-1.1.0-API文档-中英对照版.zip

    赠送jar包:scala-parser-combinators_2.12-1.1.0.jar; 赠送原API文档:scala-parser-combinators_2.12-1.1.0-javadoc.jar; 赠送源代码:scala-parser-combinators_2.12-1.1.0-sources.jar; 赠送Maven依赖信息...

    scala-compiler-2.11.8-API文档-中英对照版.zip

    赠送jar包:scala-compiler-2.11.8.jar; 赠送原API文档:scala-compiler-2.11.8-javadoc.jar; 赠送源代码:scala-compiler-2.11.8-sources.jar; 赠送Maven依赖信息文件:scala-compiler-2.11.8.pom; 包含翻译后...

    scala-parser-combinators-2.11-1.0.4-API文档-中文版.zip

    赠送jar包:scala-parser-combinators_2.11-1.0.4.jar; 赠送原API文档:scala-parser-combinators_2.11-1.0.4-javadoc.jar; 赠送源代码:scala-parser-combinators_2.11-1.0.4-sources.jar; 赠送Maven依赖信息...

    scala-java8-compat_2.11-0.7.0-API文档-中英对照版.zip

    赠送jar包:scala-java8-compat_2.11-0.7.0.jar; 赠送原API文档:scala-java8-compat_2.11-0.7.0-javadoc.jar; 赠送源代码:scala-java8-compat_2.11-0.7.0-sources.jar; 赠送Maven依赖信息文件:scala-java8-...

    scala-java8-compat_2.11-0.7.0-API文档-中文版.zip

    赠送jar包:scala-java8-compat_2.11-0.7.0.jar; 赠送原API文档:scala-java8-compat_2.11-0.7.0-javadoc.jar; 赠送源代码:scala-java8-compat_2.11-0.7.0-sources.jar; 赠送Maven依赖信息文件:scala-java8-...

    scala-xml_2.12-1.0.6-API文档-中文版.zip

    赠送jar包:scala-xml_2.12-1.0.6.jar; 赠送原API文档:scala-xml_2.12-1.0.6-javadoc.jar; 赠送源代码:scala-xml_2.12-1.0.6-sources.jar; 赠送Maven依赖信息文件:scala-xml_2.12-1.0.6.pom; 包含翻译后的API...

    scala-xml_2.11-1.0.4-API文档-中英对照版.zip

    赠送jar包:scala-xml_2.11-1.0.4.jar; 赠送原API文档:scala-xml_2.11-1.0.4-javadoc.jar; 赠送源代码:scala-xml_2.11-1.0.4-sources.jar; 赠送Maven依赖信息文件:scala-xml_2.11-1.0.4.pom; 包含翻译后的API...

    scala-2.12.14.zip&scala-2.12.11.tgz Linux版本压缩包.rar

    标题提到的"scala-2.12.14.zip&scala-2.12.11.tgz"是Scala的不同版本,针对不同的操作系统进行了打包。Windows用户可以使用".zip"格式的文件,而Linux用户则适合使用".tgz"格式的文件。这里我们主要关注Linux版本的...

    scala-parser-combinators_2.11-1.0.4-API文档-中英对照版.zip

    赠送jar包:scala-parser-combinators_2.11-1.0.4.jar; 赠送原API文档:scala-parser-combinators_2.11-1.0.4-javadoc.jar; 赠送源代码:scala-parser-combinators_2.11-1.0.4-sources.jar; 包含翻译后的API...

    scala-xml_2.11-1.0.1-API文档-中文版.zip

    赠送jar包:scala-xml_2.11-1.0.1.jar; 赠送原API文档:scala-xml_2.11-1.0.1-javadoc.jar; 赠送源代码:scala-xml_2.11-1.0.1-sources.jar; 赠送Maven依赖信息文件:scala-xml_2.11-1.0.1.pom; 包含翻译后的API...

    mongo-scala-drive的使用demo

    在 Scala 中与 MongoDB 进行交互,通常我们会使用 `mongo-scala-driver`,而不是 `mongo-java-driver`,因为 Scala 驱动提供了更符合 Scala 语言特性的 API 设计。本示例将详细介绍如何使用 `mongo-scala-driver` ...

    scala-compiler-2.11.12-API文档-中文版.zip

    赠送jar包:scala-compiler-2.11.12.jar; 赠送原API文档:scala-compiler-2.11.12-javadoc.jar; 赠送源代码:scala-compiler-2.11.12-sources.jar; 赠送Maven依赖信息文件:scala-compiler-2.11.12.pom; 包含...

    scala-ide-plugin-eclipse

    scala eclipse插件.对应scala版本:2.10--2.11,对应eclipes版本:4.4--...update site:http://download.scala-ide.org/sdk/lithium/e44/scala211/stable/site 下载地址:http://scala-ide.org/download/current.html

    scala-compiler-2.11.0-API文档-中文版.zip

    赠送jar包:scala-compiler-2.11.0.jar; 赠送原API文档:scala-compiler-2.11.0-javadoc.jar; 赠送源代码:scala-compiler-2.11.0-sources.jar; 赠送Maven依赖信息文件:scala-compiler-2.11.0.pom; 包含翻译后...

    scala-library-2.11.8-API文档-中文版.zip

    赠送jar包:scala-library-2.11.8.jar; 赠送原API文档:scala-library-2.11.8-javadoc.jar; 赠送源代码:scala-library-2.11.8-sources.jar; 赠送Maven依赖信息文件:scala-library-2.11.8.pom; 包含翻译后的API...

    scala-intellij-bin-2018.3.2.zip

    scala-intellij-bin-2018.3.2.zip插件,亲测可用!!!scala-intellij-bin-2018.3.2.zip插件,亲测可用!!!scala-intellij-bin-2018.3.2.zip插件,亲测可用!!!

    scala-intellij-bin-2016.3.9

    "scala-intellij-bin-2016.3.9"是针对Scala语言的一个特定版本的IntelliJ IDEA插件,该版本为2016.3.9。这个插件是专门为Scala开发者设计的,旨在提高他们在IntelliJ IDEA中的开发体验。 Scala是一种多范式编程语言...

    scala-library-2.12.1

    scala-library-2.12.1 是 Scala 编程语言的标准库文件,版本为 2.12.1。它提供了在使用 Scala 进行开发时所需的基本库支持。Scala 是一种多范式编程语言,融合了面向对象编程和函数式编程的特性,主要运行在 JVM ...

    scala-compiler-2.12.7-API文档-中英对照版.zip

    赠送jar包:scala-compiler-2.12.7.jar; 赠送原API文档:scala-compiler-2.12.7-javadoc.jar; 赠送源代码:scala-compiler-2.12.7-sources.jar; 赠送Maven依赖信息文件:scala-compiler-2.12.7.pom; 包含翻译后...

    scala-compiler-2.12.7-API文档-中文版.zip

    赠送jar包:scala-compiler-2.12.7.jar; 赠送原API文档:scala-compiler-2.12.7-javadoc.jar; 赠送源代码:scala-compiler-2.12.7-sources.jar; 赠送Maven依赖信息文件:scala-compiler-2.12.7.pom; 包含翻译后...

Global site tag (gtag.js) - Google Analytics