Scala 函数式程序设计原理

Posted paulingzhou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala 函数式程序设计原理相关的知识,希望对你有一定的参考价值。

课程地址: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:

  1. Evaluate all function arguments, from left to right
  2. Replace the function application by the function‘s right-hand side, and, at the same time
  3. 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 函数式程序设计原理的主要内容,如果未能解决你的问题,请参考以下文章

Scala 函数式程序设计原理--Types and Pattern Matching

Scala最新书籍-《函数式编程科学之Scala实战》pdf级随书代码分享

Scala函数式编程彻底精通

Scala函数式编程函数式的数据结构 下

重学scala:scala函数式编程与高阶函数

Scala基础高阶函数隐式转换AKKA编程