3.1.3 Functional Programming (Basic Concepts)
3.1.3 Functional Programming (Basic Concepts)
Imagine you have a super-smart calculator. You give it numbers and tell it to do things like "add these two numbers" or "find the square root of this number." The calculator just gives you the answer; it doesn't change anything else outside of that calculation.
Functional Programming is a style of programming that focuses on "what to calculate" rather than "how to do every step" (like procedural) or "what objects are involved" (like OOP). It treats everything as a mathematical function, where a function takes some inputs and always produces the same output, without causing any side effects (like changing other parts of the program that aren't related to its direct output).
Key Ideas:
- Functions are Central: Programs are built by combining simple, pure functions.
- "Pure" Functions: These functions are like math equations. If you give them the same input, they will always give you the same output, and they won't change anything else in the program while they're running. This makes them very predictable and easy to test.
- No Side Effects: This means a function doesn't mess with anything outside of itself. It just takes inputs, calculates, and gives an output. It doesn't print things to the screen, save files, or change variables somewhere else in the program unexpectedly.
How it Works: Functional programming is about transforming data using functions. You pass data into a function, and the function returns new data. This way of thinking often leads to code that is easier to reason about, especially in complex programs where many things are happening at once.
Example: Think of a simple math function: add(x, y) = x + y
add(2, 3)
will always be5
.add(10, 7)
will always be17
. This functionadd
is "pure" because it always gives the same output for the same input, and it doesn't change anything else when it runs.
Languages like Haskell, Lisp, and Erlang are primarily functional. Many modern languages like Python and JavaScript also include features that let you write code in a functional style.
Bibliography:
- GeeksforGeeks - Functional Programming Paradigm: https://www.geeksforgeeks.org/functional-programming-paradigm/
- freeCodeCamp.org - What is Functional Programming?: https://www.freecodecamp.org/news/what-is-functional-programming-in-javascript-and-how-to-use-it/ (Explains well even if JavaScript-focused)
- Wikipedia - Functional Programming: https://en.wikipedia.org/wiki/Functional_programming