函数式编程-1.1编程范式
编程范式
范式
Paradigm: In science, a paradigm describes distinct concepts or thought patterns in some scientific discipline.
主要的编程范式:
- 命令式 : c , c++ , java …
- 函数式 : scala , haskell , Lisp …
- logic programming : prolog …
和这种分类方式正交的:
面向对象编程
命令式语言 和 计算机
- 变量 —> 内存单元
- 变量解引用 —> 加载指令
- 变量赋值 —> 存储指令
- 控制结构 —> jumps 跳转命令
命令式语言的限制:
One tends to conceptualize data structures word-by-word.
我们需要其他技术来定义高层次的数据抽象:集合,多项式,几何图形…
理想情况下: 开发 theories of collections,shapes , strings…
什么是Theory
A theory consists of :
- one or more data types
- operations on these types
- laws that describe the relationships between values and operations
a theory does not describe mutations ! mutations mean change the thing while keeping the identity of the thing.
Consequences for Programming
If we want to implement high-level concepts following their mathmatical theories,there’s no place for mutation.
- Theories do not admit it
- Mutation 会破坏Theories 里面有用的lows
因此,让我们
- 专注于定义 theories for operators expressed as functions
- avoid mutations
- have powerful ways to abstract and compose functions.
函数式编程
- 狭义的概念: 函数式编程是指没有 变量,赋值,循环 和其他命令式控制结构的编程
- 广义上指:函数式编程enables the construction of elegant programs that focus on functions.
- 特别的:functions can be values that are produced,consumed,and composed
在函数式编程语言里面,函数是一等公民:
它们可以在任何地方定义,包括在其他函数内
像其他任何值一样,可以当做参数和返回值
有一组运算符来compose函数