This page looks best with JavaScript enabled

What Is Functional Programming

 ·  ☕ 2 min read

1. What a Programming Paradigm Is

A programming paradigm is a class of typical programming conventions. On one hand, it provides engineers with a way to model entities, linking the physical world to code; on the other hand, it provides engineers with a way of thinking about code and programs.

Programming paradigms and programming languages relate many-to-many. A single programming language may contain several paradigms — C++, for example, includes procedural and object-oriented programming. A single paradigm may also be implemented by many languages — JavaScript, Scala, and Python, for example, all support functional programming.

2. Several Common Programming Paradigms

  • Imperative

Tell the computer, statement by statement, how to do it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "fmt"

func main() {
	var a int = 1

LOOP:
	if a < 10 {
		a++
		goto LOOP
	}
	fmt.Printf("a = %d\n", a)
}
  • Declarative

Tell the computer only what you want; the common DSL languages are declarative, such as SQL and HTML.

1
SELECT * FROM Sites WHERE domain='www.chenshaowen.com'
  • Structured

Split into modules and add control logic through loops and the like.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "fmt"

func main() {
	var a int = 1
	for a < 10{
		a ++
	}
	fmt.Printf("a = %d\n", a)
}
  • Procedural

Built on structured programming, with an emphasis on function calls.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import "fmt"

func loop(a int) int{
	for a < 10 {
		a ++
	}
	return a
}

func main() {
	var a = loop(1)
	fmt.Printf("a = %d\n", a)
}
  • Object-oriented

Abstract entities with classes, express entities with objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/bin/python3

class Parent:
    def myMethod(self):
        print('调用父类方法')


class Child(Parent):
    def myMethod(self):
        print('调用子类方法')


c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法
  • Aspect-oriented

Move everything unrelated to the module outside of it; the common practices are decorators and middleware.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def mydeco(func):
    print('do some things')

    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper


@mydeco
def hello():
    print('hello')


if __name__ == "__main__":
    hello()
  • Interface-oriented

Prescribe a set of methods that must be implemented.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import "fmt"

type Duck interface{
	ToDuck()
}

type Dock1 struct{
}

func (d Dock1) ToDuck(){
	fmt.Println("ga...")
}

func main(){
	var d Duck
	d = new(Dock1)
	d.ToDuck()
}
  • Functional programming

Describe program logic through the composition of stateless functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import "fmt"

func add(a, b int) int {
	return a + b
}

func multi(a, b int) int {
	return a * b
}

func myCal(a, b func(int, int) int, c, d int) int {
	return b(a(c, d), a(c, -d))
}

func main() {
	var result = myCal(add, multi, 5, 1)
	fmt.Println(result)
}

3. Why Choose Functional Programming

  • Simpler project state management

Managing complexity is one of the challenges software engineering faces. For engineers, managing the state a program runs in is the hard part of programming. Functional programming emphasizes statelessness: apart from IO handling, there is no need to maintain the program’s own state.

  • Closer to human language

Functional programming usually draws on the declarative paradigm, telling the computer what to do in a description closer to human language. It does not ask people to imitate the way a computer thinks and tell it, instruction by instruction, how to do things.

  • Better suited to concurrency

Because functional programming maintains no state, the problem of locks does not arise; concurrency issues can be solved at the compiler and interpreter level, greatly reducing the difficulty of writing highly concurrent programs.

  • Out with the old, in with the new — styles rotate

Wheels are always being reinvented. Many ideas appeared early in the history of computing but did not always get a chance to reach the general public. Functional programming and communicating sequential processes are both like this, and so is cloud computing; styles always rotate, with a certain periodicity.

4. Keywords of Functional Programming

  • Pure function

The output depends only on the input.

  • Referential transparency

A function can be replaced by its computed result without affecting the program that calls it.

  • No side effects

It does not depend on external state.

  • Lazy evaluation

Evaluate only when needed.

  • lambda

An anonymous function, a function with no name.

  • Currying

The process of transforming a multi-parameter function into one that returns a single parameter and can keep accepting the remaining parameters.

  • Higher-order function

A function that accepts a function as a parameter or returns a function.


微信公众号
WRITTEN BY
微信公众号