Scala 2 - 4 - Lecture 1.4 - Conditionals and Value Definitions (8_49)
来源:互联网 发布:我国域名总数世界排名 编辑:程序博客网 时间:2024/04/28 11:15
在scala中,可以用val和def前缀来定义变量,例如:
val x = 1def y = "foo"
这两者的区别在于:
- val定义值时,会做call-by-value操作,
- def则会做call-by-name操作。
例如:
// 这是一个死循环 def loop: Boolean = loop // 用val定义时会做call-by-value,以下语句会block住 val x = loop // 用def定义时,是做的call-by-name。故以下语句暂时不会执行,在用到y的时候才做evaluation def y = loop陷到loop里时,用ctrl+c发中断信号终止。
函数定义中的call-by-name和call-by-value
首先思考一个问题,如何在不使用”||”和“&&”的情况下,实现如下两个函数and和or:
and(x, y) == x && y or(x, y) == x || y对于and,可以用如下方式定义:
def and(x: Boolean, y: Boolean) = if (x) y else false // 测试 and(true, true) // => true and(false, true) // => false
但是,这种定义在遇上循环的时候会有问题,例如
and(false, loop)上述语句会陷入循环,因为在我们的定义中,对于x和y参数的引用都是call-by-value的。要指定参数为call-by-name,只需要把函数定义改为如下形式即可:
def and(x: Boolean, y: => Boolean) = if (x) y else false // 测试 and(false, loop) // => false注意我们在定义参数y的时候,使用的
=>
符号。 0 0
- Scala 2 - 4 - Lecture 1.4 - Conditionals and Value Definitions (8_49)
- Lecture 2: Operators and operands; statements; branching, conditionals, and iteration
- Scala 函数式编程原理 第四课(Conditions and Value Definitions)
- Scala-2 - 6 - Lecture 1.6 - Blocks and Lexical Scope (8_00)
- Learning with python: Chapter3~4 Functions,Conditionals and Recursion
- Scala-3 - 5 - Lecture 2.5 - Functions and Data (11_50)
- Scala-3 - 7 - Lecture 2.7 - Evaluation and Operators (16_25)
- Scala-5 - 3 - Lecture 4.3 - Subtyping and Generics (15_02)
- 4 表达式与定义(Expressions and Definitions)
- Scala-3 - 4 - Lecture 2.4 - Scala Syntax Summary (4_13)
- ActionScript 3.0 - Conditionals and Loops
- Scala-4 - 2 - Lecture 3.2 - How Classes Are Organized (20_30)
- Terms, definitions, and symbols
- Lecture 2: 基础结构: RPC and threads
- Scala-5 - 1 - Lecture 4.1 - Functions as Objects (8_04)
- Scala-4 - 1 - Lecture 3.1 - Class Hierarchies (25_50)
- Scala-4 - 3 - Lecture 3.3 - Polymorphism (21_09)
- Scala-5 - 4 - Lecture 4.4 - Variance (Optional) (21_33)
- ActivityManagerService分析一:AMS的启动
- git 使用bitbucket托管xcode 搭建多人协作开发
- Apple Catching(3维dp)
- c语言之头文件的使用
- JNI-->C调用Java语言
- Scala 2 - 4 - Lecture 1.4 - Conditionals and Value Definitions (8_49)
- Android插件原理剖析
- 颜色特征
- 区间为状态的dp Milking Time
- div背景图片自适应
- Android应用开发on Rayeager PX2好用工具推荐
- Fragment 几点特征
- android启动各种系统服务
- 安装nodejs