[ Draft ]
最近在写ratpack,突然funcitonal programming的许多想法又跳了出来。查找资料过程中,读了一章红宝书
Functiona Programming in Scala
发现有许多新的理解。一开心打算重新拜读一遍。在这也做个笔记,或思想的总结。给未来的自己看。
Chapter 01
What’s functional programming
Side effect example:
- Modifying a variable
- Modifying a data structure in place
- Setting a field on an object
- Throwing an exception or halting with an error
- Printing to the console or reading user input
- Reading from or writing to a file
- Drawing on the screen
Two import concets
referential transparency
An expression e is referentially transparent if, for all programs p, all occurrences of e in p can be replaced by the result of evaluating e without affecting the meaning of p. A function f is pure if the expression f(x) is referentially transparent for all referentially transparent x.
substitution model
Referential Transparency (RT)
In any program, the expression can be replaced by its result without changing the meaning of the program. And we say that a function is pure if calling it with RT arguments is also RT.
For example, 2 + 3 is an expression that applies the pure function + to the values 2 and 3 (which are also expressions). This has no side effect. The evaluation of this expression results in the same value 5 every time. In fact, if we saw 2 + 3 in a program we could simply replace it with the value 5 and it wouldn’t change a thing about the meaning of our program.
Substitution Model
Referential transparency forces the invariant that everything a function does is represented by the value that it returns, according to the result type of the function. This constraint enables a simple and natural mode of reasoning about program evaluation called the substitution model.
We simply look at the function’s definition and substitute the arguments into its body. Even if you haven’t used the name “substitution model,” you have certainly used this mode of reasoning when thinking about your code.