在COURSERA跟设计者学习Scala
编码风格
- 避免使用
isInstanceOf
或者asInstanceOf
进行类型转换
- 使用两个空格进行缩进
- 不需要使用分号
- 避免使用
return
函数式编程
- 不可变性
- 利于模块化
- 函数是一等公民,可以作为变量,参数等
- 适合并行多核环境和云计算
Call-by-name & Call-by-value
- substitution model
- 只要保证是纯函数并有中止条件,两种调用方式结果一致
- Call-by-name 函数体中没有用到的参数可以不计算
- Call-by-value 只对参数计算一次
代码块与作用域
- avoid “name-space pollution”
尾递归
函数调用自身是最后一步操作,栈可以重用避免溢出
- Base cases. You must always have some base cases, which can be solved without recursion.
- Making progress. For the cases that are to be solved recursively, the recursive call must
always be to a case that makes progress toward a base case.
- Design rule. Assume that all the recursive calls work.
- Compound interest rule. Never duplicate work by solving the same instance of a problem in
separate recursive calls.
高阶函数
函数可以作为__参数__或__返回值__
柯里化
- 接受多个参数的函数变换为接受一个参数的函数,并返回接受余下参数的新函数
Finding fixed point
- 欺负我数学不好 T_T
- fixed point: 如果一个数x满足f(x) = x, 就称之为方程的fixed point. 没理解错的话,就是y=x和y=f(x)的交点
- 于是可通过重复的迭代 x, f(x), f(f(x)), f(f(f(x))), … 求出
Syntax summary
Types
Type = SimepleType | FunctionType
FunctionType = SimpleType '=>' Type
SimpleType = Ident
Types = Type { ',' Type }
Expressions
Expr = InfixExpr | FunctionExpr | if '(' Expr ')' Expr else Expr
InfixExpr = PrefixExpr | InfixExpr Operator InfixExpr
Operator = ident
PrefixExpr = ['+' | '-' | '!' | '~'] SimepleExpr
SimepleExpr = ident | literal | SimepleExpr '.' ident | Block
FunctionExpr = Bindings '=>' Expr
Bindings = ident [':' SimpleType] | '(' [Binding {',' Binding}] ')'
Bingding = ident [':' Type]
Block = '{' {Def ';'} Expr '}'
Definitions
Def = FunDef | ValDef
FunDef = def ident {'(' [Parameters] ')'} [':' Type] '=' Expr
ValDef = val ident [':' Type] '=' Expr
Parameter = ident ':' [ '=>' ] Type
Parameters = Parameter {',' Parameter}