- Functional Programming Explained in Python, JavaScript, and Java
- Original author: The Educative Team
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: z0gSh1u
- Proofreader: regonCao, NieZhuZhu, ICicle198514
Functional programming — described using Python, JavaScript, and Java
Functional programming (FP) is the process of building software by combining pure functions. Today, employers are looking for programmers who can take advantage of multiple paradis to solve problems. Functional programming is especially popular because of its efficiency and extensibility to solve the latest problems.
But how do you make the transition from OOP to FUNCTIONAL programming (FP)?
Today, we’ll explore the core concepts of functional programming and show you how to implement them in Python, JavaScript, and Java.
This article covers the following:
- What is functional programming
- Functional programming languages
- Related concepts of functional programming
- Functional programming — Using Python
- Functional programming — Using JavaScript
- Functional programming — Using Java
- What to learn next
What is functional programming
Functional programming is a declarative programming paradigm in which programs are built based on applying sequences of functions rather than statements.
Each function takes an input and always returns a consistent output for the same input, without changing the state of the program or being affected by it.
These functions perform a single operation and can be sequentially combined to perform complex operations. The functional programming paradigm makes code highly modular because functions can be reused in a program and can be called, passed as arguments, or returned.
Pure functions have no side effects and are not dependent on global variables or states.
Functional programming is used when the solution can be easily expressed as a function and has little or no physical implications. Functional programming is better at implementing mathematical functions, with no entity relation between intermediate or final values, than object-oriented programming, which is based on real object code modeling.
Common applications of functional programming include AI design, machine learning classification algorithms, economic programs, or advanced mathematical functional models.
In short: Functional programs perform many pure, single-function functions sequentially to solve complex mathematical or nonphysical problems.
The advantages of functional programming
- Simple debugging: Pure functions and immutable data make it easy to find where to set variable values. There are fewer factors affecting pure functions, so it’s easier to find buggy parts.
- Delayed computation: A functional program computes only when the result is needed. This allows the program to reuse previous calculations and save running time.
- Modularity: Pure functions do not depend on external variables or states, which means they can be easily reused in programs. Also, functions perform only a single operation or calculation, ensuring that you can reuse functions without introducing additional code.
- Better readability: Functional programs are easier to read because the behavior of each function is immutable and isolated from the state of the program. This allows you to predict the behavior of each function most of the time by virtue of its name.
- Parallel programming: It is easier to build parallel programs using a functional programming approach because immutable variables reduce changes within the program. Each function only needs to process its own input, and you can assume that the state of the program stays the same most of the time.
Functional programming languages
Not all programming languages support functional programming. Some languages, such as Haskell, are designed by nature to be functional programming languages. Other languages, such as JavaScript, have both functional and object-oriented programming capabilities. The rest are languages that don’t support functional programming at all.
A purely functional programming language
- Haskell: This is the most popular functional programming language. It is memory-safe, has good garbage collection, and is fast thanks to early machine code compilation. Haskell’s rich and static type system allows you to use unique algebraic and polymorphic types to make functional programming more efficient and readable.
- Erlang: This language, along with its derivative Elixir, set the bar for functional languages in concurrent system development. Although not as popular or widely used as Haskell, it is often used in back-end development. Erlang has also become increasingly popular recently in developing extensible messaging apps like WhatsApp and Discord.
- Clojure: This language is a dialect of Lisp functions that runs on the JVM as first-class citizens. It is basically a functional programming language that supports both mutable and immutable data structures. It is less rigorous than some of the other functional languages here. If you like Lisp, you’ll like Clojure, too.
- F# : F# is similar to Haskell (they belong to the same language group), but with fewer advanced features. It also has some support for object-oriented programming.
Languages that support functional programming
- Scala: Scala supports both functional and object-oriented programming. Its most interesting feature is a strong static typing system similar to Haskell to help you write robust functional programs. Scala was designed to address the criticisms of Java, so it’s a good language for Java developers who want to experiment with functional programming.
- JavaScript: While functions are not first-class citizens, JavaScript stands out for functional programming because of its asynchronous nature. JavaScript also supports basic functional programming features such as lambda expressions and deconstruction. Together, these features make JavaScript the best multiparadigm language for functional programming.
- Python, PHP, C++ : these multiparadigm languages support functional programming, but not as fully as Scala and JavaScript.
- Java: Java is a multi-objective language, but it leads the way in object-oriented programming. The addition of Lambda expressions gives you limited access to a more functional programming style. Java is still an object-oriented language that does functional programming, but it’s missing a lot of key features that make the transition not particularly worthwhile.
Concepts related to functional programming
When writing functional programs, you need to understand the following core concepts:
Variables and functions
The core of functional programs are variables and functions, not objects and methods. You should avoid using globals, because mutable globals can make your program hard to read and lead to impure functions.
Pure functions
Pure functions have two properties:
- No side effects;
- For the same input, always give the same output.
Side effects occur when a function changes the state of the program, overwrites input variables, or changes anything else while generating output values. Pure functions are less buggy because side effects can complicate the state of a program.
Function “referential transparency” means that the output of a function can change without changing the program. This concept ensures that you can create single-function functions and get consistent output for the same input.
Reference transparency is only possible if the function does not affect program state or if it tries to accomplish more than one operation.
Immutability and state
Immutable data or state, once set, cannot be changed, providing a stable environment for the consistency of function output. It is a programming best practice that functions give the same output for the same input, regardless of program state. If a function must depend on a state, that state must be immutable to guarantee the consistency of the function’s output.
Functional programming avoids functions that have shared state (multiple functions depend on the same state) and functions that change state (functions depend on another mutable function) because they reduce the modularity of the program. If you have to use functions with shared states, make the states immutable.
recursive
One notable difference between object-oriented programming and functional programming is that functional programming avoids structures such as if-else statements or loops that produce different output each time they are executed.
Functional programs use recursion in place of all iteration loops.
The function is a first-class citizen
Functions in functional programming languages are considered data types and can be used just like any other value. For example, we can construct an array of functions, pass functions as arguments, or store functions in variables.
Higher-order functions
Higher-order functions can take other functions as arguments or return functions. Higher-order functions make our function calls and the abstraction of actions much more flexible.
Function composition
Functions can be executed sequentially to perform complex operations. The result of each function’s execution is passed as an argument to the next function. This allows you to call a series of functions from a single function call.
Functional programming — Using Python
Python, as a multiparadigm language, partially supports functional programming. Some mathematical problems can be implemented more easily in Python with the help of functional programming.
One of the most difficult changes to start using functional programming is to reduce the number of classes. Classes in Python have mutable attributes, which makes it difficult to create pure, immutable functions.
Try to keep most of your code at the module level and use classes only when necessary.
Let’s look at how to implement pure, immutable functions and first-class citizen functions in Python. Then, we’ll learn the syntax of function composition.
A pure, immutable function
Many Of Python’s built-in data structures are immutable by default:
- integer
- float
- boolean
- string
- Unicode
- tuple
Tuples are especially useful as immutable forms of arrays.
Python code to test the immutability of tuples
tuple1 = (0.1.2.3)
tuple1[0] = 4
print(tuple1)
Copy the code
This code produces an error because it tries to reassign an immutable tuple object. Functional Python programs should make more use of these immutable data structures to implement pure functions.
Here is a pure function, because it has no side effects and always gives the same output for the same input:
def add_1(x) :
return x + 1
Copy the code
The function is a first-class citizen
Functions are considered objects in Python. Here is a brief introduction to using functions in Python:
Function as object
def shout(text) :
return text.upper()
Copy the code
Functions are passed as arguments
def shout(text) :
return text.upper()
def greet(func) :
Store the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print greeting
greet(shout)
Copy the code
Returns a function from a function
def create_adder(x) :
def adder(y) :
return x+y
return adder
Copy the code
Function composition
To combine functions in Python, we use Lambda expressions. This allows us to call multiple functions simultaneously in a single function call.
import functools
def compose(*functions) :
def compose2(f, g) :
return lambda x: f(g(x))
return functools.reduce(compose2, functions, lambda x: x)
Copy the code
In line 4, we define compose2, which takes two functions f and g as arguments. In line 5, we return a new function representing a combination of f and g.
Finally, on line 6, we return the result of the combined function.
Functional programming — Using JavaScript
JavaScript has provided functional programming capabilities for a long time thanks to its support for “functions are first-class citizens.” Recently, functional programming in JavaScript has become more popular because of the performance benefits it provides in frameworks like Angular and React.
Let’s take a look at how to implement functional programming using JavaScript. We’ll focus on how to express the core concepts of functional programming: pure functions, functions being first-class citizens, and function combinations.
Pure and immutable functions
To create pure functions in JavaScript, we must replace traditional methods with functional methods such as const, concat, and filter().
The let keyword declares a variable quantity. Switching to const guarantees immutability because it prevents reassignment.
const heightRequirement = 46;
function canRide (height) {
return height >= heightRequirement;
}
Copy the code
We also need to manipulate arrays functionally. The way we normally add elements to an array is push(). However, push() modifies the original array and is therefore impure.
Instead, we use the functional equivalent of concat(). This method returns a new array containing the original element and the new element, and the original array is not modified.
const a = [1.2]
const b = [1.2].concat(3)
Copy the code
To remove elements from an array, we usually use the pop() and slice() methods. However, since they modify the original array, they are not functional. Instead, we use filter(), which creates a new array of elements that can pass the conditional test.
const words = ['spray'.'limit'.'elite'.'exuberant'.'destruction'.'present'];
const result = words.filter(word= > word.length > 6);
Copy the code
The function is a first-class citizen
JavaScript supports functions as first-class citizens by default. Here’s a quick look at what you can do with functions in JavaScript.
Assign a function to a variable
const f = (m) = > console.log(m)
f('Test')
Copy the code
Put the function in an array
const a = [
m= > console.log(m)
]
a[0] ('Test')
Copy the code
Pass functions as arguments
const f = (m) = > () = > console.log(m)
const f2 = (f3) = > f3()
f2(f('Test'))
Copy the code
Returns a function from a function
const createF = () = > {
return (m) = > console.log(m)
}
const f = createF()
f('Test')
Copy the code
Function composition
In JavaScript, we can combine functions using chained function calls:
obj.doSomething()
.doSomethingElse()
Copy the code
Alternatively, we can pass the result of a function’s execution to the next function:
obj.doSomething(doThis())
Copy the code
If we want to combine more functions, we can use LoDash to simplify the process. Specifically, we will use the compose property. It takes a function as the first argument, followed by a series of function calls.
The first function in the argument takes the original call argument, and subsequent function calls rely on the return value of the previous function.
import { compose } from 'lodash/fp'
const slugify = compose(
encodeURIComponent,
join(The '-'),
map(toLowerCase),
split(' ')
)
slufigy('Hello World') // hello-world
Copy the code
Functional programming — Using Java
Java doesn’t really support functional programming the way Python and JavaScript do. However, we can use Lambda expressions, flows, and anonymous classes to simulate functional programming behavior.
The Java compiler was not designed for functional programming after all, and therefore does not provide many of its benefits.
Pure and immutable functions
Some data types built into Java are immutable:
- integer
- boolean
- byte
- short
- string
You can also create custom immutable classes with the final keyword:
// An immutable class
public final class Student
{
final String name;
final int regNo;
public Student(String name, int regNo)
{
this.name = name;
this.regNo = regNo;
}
public String getName(a)
{
return name;
}
public int getRegNo(a)
{
returnregNo; }}Copy the code
The final keyword applied to a class prevents subclass construction. Final on name and regNo makes it impossible to modify objects after they have been constructed.
This class also has a constructor with parameters and Getter methods on all properties. Because there are no Setter methods, this class is immutable.
The function is a first-class citizen
Java can use Lambda expressions to implement functions as first-class citizens. Lambda expressions accept a series of expressions like a method, but need not themselves be named or defined in advance.
Lambda expressions can be used instead of ordinary functions because they are also considered standard class objects that can be passed or returned.
// The function is first-class citizen
Supplier<String> lambda = myObject::toString;
// Higher order function
Supplier<String> higherOrder(Supplier<String> fn) {
String result = fn.get();
return () -> result;
}
Copy the code
Function composition
Java has an Interface: Java. Util. The function. The function. It provides a means of composing functions. The compose method first executes the incoming function (multiplyByTen) and passes the return value to the external function (square). The andThen method executes the external functions first, then the functions in the parameters.
Function<Integer, Integer> square = (input) -> input * input;
Function<Integer, Integer> multiplyByTen = (input) -> input * 10;
COMPOSE: the function in the COMPOSE argument will be run first
Function<Integer, Integer> multiplyByTenAndSquare = square.compose(multiplyByTen);
// ANDTHEN: The function in the argument will be run
Function<Integer, Integer> squareAndMultiplyByTen = square.andThen(multiplyByTen);
Copy the code
On lines 1 and 2, we first create two functions square and multiplyByTen. Then, on line 5 and line 8, we create two composite functions: multiplyByTenAndSquare and squareAndMultiplyByTen, each of which is passed two arguments (the first argument is the argument passed to the composite function when called, The second argument is the return value of the function called first.
Both of these combinatorial functions eventually perform the function of the original partition function, but in different order. You can try to execute both combinatorial functions using the same input.
What to learn next
Today, we discussed some of the basic concepts of functional programming and explored how these core concepts are represented in Python, JavaScript, and Java.
One of the functional programming languages making a comeback is Scala. Many tech giants, such as Twitter and Facebook, use Scala and hire technical staff. As an introduction to functional programming languages, your next step should be Scala.
Have fun!
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.