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

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
主站蜘蛛池模板: 伊金霍洛旗| 凤城市| 濮阳县| 成安县| 炉霍县| 上饶市| 新巴尔虎右旗| 义马市| 柏乡县| 金阳县| 青阳县| 图木舒克市| 炉霍县| 外汇| 古田县| 沁水县| 荔浦县| 密云县| 阳山县| 郑州市| 云阳县| 房产| 稷山县| 淮滨县| 东方市| 威远县| 贡嘎县| 和平区| 伊通| 澄江县| 塔河县| 临猗县| 南投县| 积石山| 义马市| 宁阳县| 建瓯市| 泌阳县| 塔河县| 洪洞县| 太谷县|