Skip to content

Functional programming

“functional programming"即”函数式编程“。

wikipedia Functional programming

NOTE: 维基百科的这篇文章有些难以理解,我觉得理解Functional programming的关键有:

Functional programming是一种Declarative programming

其次是:

treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data

这说明在functional programming中,是没有我们熟知的那些statement,比如 assignment,因为 assignment可能会change state,所以在functional programming中,仅仅只有expression。

需要结合具体例子来进行理解也是一种捷径,在原文的Coding styles中给出的例子就非常易懂。

按照,functional programming的定义,使用higher-order function不一定是functional programming。

在维基百科Template metaprogramming#Components of template metaprogramming中提及:

Template metaprograms have no mutable variables— that is, no variable can change value once it has been initialized, therefore template metaprogramming can be seen as a form of functional programming. In fact many template implementations implement flow control only through recursion, as seen in the example below.

wikimili Functional programming

Higher-order Function

utexas CS 378, Symbolic Programming#Functional Programming

A functional program is one with no side effects:

  • changing a global variable
  • updating a database
  • printing

If we call sin(x), it will just return a value, but will have no side effects.

Functional programming does everything by composition of functions:

guacamole:
season(mash(slice(peel(wash(avocado)))))

Functions are composed so that the output of one function is the input of the next function(pipelined).

Functional programming in distributed computing

utexas CS 378, Symbolic Programming#Functional Programming:

Functional programming works well with distributed cloud computing: the function can be replicated on many servers and executed in parallel on massive amounts of data.

Promise and future

Promise and future起源自functional programming,关于Promise and future,参见工程Parallel-computing的Programming-model\Promise-future章节。

Map (parallel pattern)

https://infogalactic.com/info/Map_(parallel_pattern)

Pattern

functional programming中的一种非常常见的pattern是在工程discrete的Relation-structure-computation\Computation\Repetition章节中提出的对structure顺序执行某个computation。

关于functional programming,参见:

1) cornell Higher-order Programming

2) https://softwarefoundations.cis.upenn.edu/lf-current/Poly.html

3) Python Functional Programming HOWTO

4) wikimili Fold (higher-order function)

下面是一些非常常见的模式,它们都是基于one-by-one computation model。

apply/map

对一个data structure中的每个元素都执行同一个函数

https://infogalactic.com/info/Map_(higher-order_function)

fold/reduce

参见 C++ fold

https://en.wikipedia.org/wiki/Fold_(higher-order_function)

https://wikimili.com/en/Fold_(higher-order_function)

filter

对一个sequence进行过滤

https://infogalactic.com/info/Filter_(higher-order_function)

Convolution

https://infogalactic.com/info/Convolution_(computer_science)