官术网_书友最值得收藏!

What is functional programming?

Functional programming is a paradigm (a style of structuring your programs). In essence, the focus is on transforming data with expressions (ideally such expressions should not have side effects). Its name, functional, is based on the concept of a mathematical function (not in sub-routines, methods, or procedures). A mathematical function defines a relation between a set of inputs and outputs. Each input has just one output. For example, given a function, f(x) = X2; f(5) is always 25.

The way to guarantee, in a programming language, that calling a function with a parameter always returns the same value, is to avoid accessing to mutable state:

fun f(x: Long) : Long { 
return x * x // no access to external state
}

The f function doesn't access any external state; therefore, calling f(5) will always return 25:

fun main(args: Array<String>) {
var i = 0

fun g(x: Long): Long {
return x * i // accessing mutable state
}

println(g(1)) //0
i++
println(g(1)) //1
i++
println(g(1)) //2
}

The g function, on the other hand, depends on mutable state and returns different values for the same.

Now, in a real-life program (a Content Management System (CMS), shopping cart, or chat), state changes. So, in a functional programming style, state management must be explicit and careful. The techniques to manage state change in functional programming will be covered later. 

A functional programming style will provide us with the following benefits:

  • Code is easy to read and test: Functions that don't depend on external mutable state are more accessible to reason about and to prove
  • State and side effects are carefully planned: Limiting state management to individual and specific places in our code makes it easy to maintain and refactor
  • Concurrency gets safer and more natural: No mutable state means that concurrency code needs less or no locks around your code
主站蜘蛛池模板: 黄浦区| 武山县| 修文县| 文山县| 南漳县| 怀宁县| 抚松县| 绥芬河市| 溧水县| 西吉县| 江津市| 醴陵市| 乳山市| 手游| 元谋县| 大新县| 新郑市| 邢台市| 常宁市| 建德市| 木里| 嘉祥县| 会理县| 萝北县| 安宁市| 北票市| 民权县| 莫力| 资溪县| 莎车县| 清涧县| 博客| 顺昌县| 怀集县| 朝阳县| 榆社县| 乌拉特后旗| 仁化县| 叶城县| 福贡县| 汉阴县|