首页 > 代码库 > Scala 函数式程序设计原理(1)
Scala 函数式程序设计原理(1)
课程地址:https://www.coursera.org/learn/progfun1/home/welcome
1.1 Programming Paradigms
- In a restricted sense, a functional programming language is one which does not have mutable variables, or imperative control structures.
- In a wider sense, a functional programming language enables the construction of elegant programs that focus on functions.
- In particular, functions in a FP language are first-class citizens. This meas
- they can be defined anywhere, including inside other functions
- like any other value, they can be passed as parameters to functions and returned as results
- as for other values, there exists a set of operators to compose functions
1.2 Elements of Programming
Evaluation of Function Applications:
- Evaluate all function arguments, from left to right
- Replace the function application by the function‘s right-hand side, and, at the same time
- Replace the formal parameters of the function by the actual arguments
Example:
sumOfSquares(3, 2+2) sumOfSquares(3, 2+2)
sumOfSquares(3, 4) square(3) + square(2+2)
square(3) + sqaure(4) 3 * 3 + (2+2) * (2+2)
3 * 3 + sqaure(4) 9 + (2+2) * (2+2)
9 + sqaure(4) 9 + 4 * (2+2)
9 + 4 * 4 9 + 4 * 4
9 + 16 9 + 16
25 25
call-by-value call-by-name
1.3 Evaluation Strategies and Termination
def first(x: Int, y: Int) = x
first(1, loop)
CBN: 1
CBV: first(1, loop) => first(1, loop) => ...
in scala, using CBV: more efficiency && less side effect
=> pass call by name
1.4 Conditions and Value Definations
def: call by name
val: call by value
def loop: Boolean = {
if(loop) loop else false
}
def a = loop //loop
val b = loop //no result, because in val, it will calculate value of function loop first
1.6 Blocks and Lexical Scope
block is delimited by braces { ... }, it contains a sequence of definitions or expressions
1.7 Tail Recursion
In general, if the last action of a function consists of calling a function (which may be the same), one stack frame would be sufficient for both functions. Such calls are called tail-calls.
Scala 函数式程序设计原理(1)