Functional Programming
What Is Functional Programming?
Functional programming (FP) is a way of writing code that treats functions like building blocks. Instead of changing data step by step, you create new values by applying pure functions. This style makes programs easier to understand, test, and reuse.
Pure Functions
A pure function always gives the same result when you give it the same inputs, and it never changes anything outside itself.
- Deterministic –
add(2, 3)will always return5. - No Side Effects – it doesn’t modify global variables, files, or the screen.
Because pure functions don’t rely on hidden state, they are predictable and safe to run in parallel.
Higher‑order Functions
In FP, functions can be passed around just like numbers or strings.
- Take Functions As Arguments –
map(array, fn)appliesfnto each element. - Return Functions –
makeAdder(5)could return a new function that adds 5 to its input.
Higher‑order functions let you create powerful, reusable tools with just a few lines of code.
Why Use Functional Programming?
- Readability – Code reads like a math formula, making it clear what it does.
- Reliability – Pure functions reduce bugs caused by unexpected changes.
- Concurrency – Since pure functions don’t share state, they work well on multiple cores.
Functional programming isn’t a replacement for other styles; it’s a toolbox that helps you write cleaner, safer code. Try experimenting with pure functions and higher‑order functions in a language you know, and see how the ideas fit together.