Ebben a cikkben megismerheti a funkcionális programozást és annak előnyeit.
Bevezetés a funkcionális programozásba
A funkcionális programozás (FP) egyfajta paradigma vagy minta a számítástechnikában. Minden az FP függvényeinek segítségével történik, és az alapvető építőelemek csak függvények.
A tisztán funkcionális programozást támogató programozási nyelvek a következők:
- Haskell
- Bezárás
- Scala
- SQL
A funkcionális programozást támogató programozási nyelvek, valamint más programozási paradigmák a következők:
- Piton
- Javascript
- C ++
- Rubin
Mivel a név funkcionálisnak mondja, a legtöbb programozó gondolkodik a matematikai függvényeken. Az FP-vel nem ez a helyzet. Ez csak egy absztrakció a valós komplex problémák egyszerű és hatékony megoldására.
Az objektumorientált programozási korszak előtt a szoftveripar teljesen a funkcionális programozástól függ. Ez a paradigma néhány évtizeden át rázta a szoftveripart. Van néhány probléma a funkcionális programozással, és ezért költöztek az Object-Oriented paradigmába. Az FP-vel kapcsolatos kérdéseket a cikk később tárgyalja.
Ez csak a funkcionális programozás bevezetéséről szól. Most először is meg kell tanulnunk, mi a függvény.
Funkciók
Mielőtt feltárnám a tényleges definíciót, szeretnék elmagyarázni egy helyzetet, hogy megtudjam, hol használhatjuk az FP-t. Tegyük fel, hogy kódot ír egy alkalmazás létrehozásához. Fejlesztési útja során szeretné felhasználni néhány sor (100) kódját különböző helyeken. Az Ön alkalmazásához a funkciók hasznosak. Egy helyen írhatunk függvényeket, és a program bármely részéről hozzáférhetünk ezekhez a funkciókhoz. A funkcionális programozás a következő tulajdonságokkal rendelkezik:
- Csökkenti a kód redundanciáját.
- Javítja a modularitást.
- Segít nekünk összetett problémák megoldásában.
- Növeli a karbantarthatóságot.
Nézzük meg a függvény tényleges meghatározását:
A Function egy meghatározott kódblokk, amelyet a program egy adott feladatának végrehajtására használnak.A legnépszerűbb funkciók a következők:
- Általános funkciók
- Nyílfunkciók
- Névtelen funkciók
Általános funkciók
Az általános függvények nem más, mint azok a függvények, amelyeket a programozó gyakran használ egy adott feladat végrehajtására. A Javascriptben egy általános függvény deklarálásának szintaxisa:
function functionName(parameters) { // code to be executed}
function - Ez egy kulcsszó, amely szükséges egy funkció deklarálásához.
functionName - A függvénymunka alapján meg lehet nevezni.
paraméterek - Bármennyi paramétert átadhatunk egy függvénynek.
A deklarált funkciók nem kerülnek azonnal végrehajtásra. Ezeket „későbbi felhasználásra elmentjük”, és később végrehajtjuk, amikor meghívjuk őket (felhívjuk őket).Meg kell hívnunk a függvényt, amikor végre akarjuk hajtani azt a kóddarabot, amelyet egy függvényen belül adunk vissza.
Az általános funkciók a következők szerint vannak osztályozva:
Argumentum nélküli funkciók
Nem kell semmilyen argumentumot átadnunk a függvénynek.
// Function Declaration
function sayHello(){ alert('Hello...!');}
// Calling the functionsayHello()
Amikor felhívjuk a függvényt a Hello () kifejezésre, akkor Hello-ként hozza létre a riasztási üzenetet.
Argumentum függvények
Az ilyen típusú függvényekben érveket adunk át nekik.
Példa
// Declaring a Function
function add(num1, num2){ return num1 + num2;}
// Function Call
var result = add(7, 11);
console.log(result);
A függvény deklarálásakor átadott argumentumokat (pl. Num1, num2) formális paraméterként hívják meg .
A (7, 11) függvény meghívásakor átadott argumentumokat tényleges paraméterként hívjuk meg .
A Function általában visszaad valamilyen értéket, és ennek az értéknek a visszaadásához a return kulcsszót kell használnunk . Ha egy függvény valamilyen értéket ad vissza, az azt jelenti, hogy nem nyomtat nekünk kimenetet, csak a végső kimenetet adja vissza. A mi felelősségünk ezt az eredményt kinyomtatni. A fenti programban a függvény visszaadja az értéket, és ezt az értéket átadom az 'eredmény' változónak. Most a függvény átadja az eredményt az 'eredmény' változónak.
A Javascript funkciók különlegessége
Ha több argumentumot ad meg, mint a deklarált szám, akkor nem kap hibát. De más programozási nyelveken, mint a Python, a C, a C ++, a Java stb. ... hibát fogunk kapni. A Javascript az igényeik alapján mérlegeli.
Példa
// Calling the function with more number of arguments than the declared number
var result1 = add(2, 4, 6);console.log(result1);
var result2 = add(2);console.log(result2);
Kimenet

Ha kevesebb argumentumot ad meg, mint a deklarált szám, akkor mi sem fogunk hibát kapni. De nem tudjuk megjósolni a program kimenetét, mert a függvény funkcionalitása alapján a kimenet elő lesz állítva.
Változó argumentum funkció
A Javascript függvények legnagyobb előnye, hogy tetszőleges számú argumentumot átadhatunk a függvénynek. Ez a szolgáltatás segíti a fejlesztőket a hatékonyabb és következetesebb munkában.
Példa
// Creating a function to calculate sum of all argument numbers
function sumAll(){
let sum = 0;
for(let i=0;i
return sum;
}
// Calling the sumAll function
sumAll();
sumAll(1,2,3,12,134,3234,4233,12,3243);
Output

Original text

This is all about general functions that are used to perform our complex task in a simple manner. Now let’s discuss some advanced functions introduced in ES6 called Arrow Functions.
Arrow Functions
An arrow function expression is a syntactically compact alternative to a regular function expression. It doesn’t have its own bindings to the this, super, arguments or new.target keywords. Arrow function expressions are ill-suited as methods. They cannot be used as constructors.
One of the most loved features in Es6 are Arrow functions. This arrow function helps developers time and simplify function scope.The syntax for the arrow function is:
const functionName = (parameters) => { // code to be executed}
(OR)
var functionName = (parameters) => { // code to be executed}
(OR)
let functionName = (parameters) => { // code to be executed}
Examples for Arrow Functions
Eg 1
Creating an Arrow function to say a welcome message to the users.
// Creating a Welcome function
let sayHello = () => { return 'Welcome to Javascript World...!';}
// Calling the function
console.log(sayHello())
Output

Eg 2
In this example, we are creating an Arrow function to generate the greatest of all numbers that are passed as an argument.
let maxNumber = (a,b,c,d) => {
if(a > b && a > c && a > d) return a; else if(b > a && b > c && b>d) return b; else if(c > a && c > b && c > d) return c; else return d;}
// Calling the function
console.log(maxNumber(1,2,4,3));
Output:

Combination of Variable Arguments with Arrow Functions
Since we are working with an arrow function, it doesn’t support the arguments array by default like general function. It is our responsibility to declare explicitly that it supports the variable number of arguments
Eg 3
let varArgSum = (...args) => { let sum = 0;
for(let i=0;i
return sum;
}
// Calling the Function
console.log(varArgSum());
console.log(varArgSum(1,2,3,4,5,6,7,8,9,10));
Output

This is how we can combine a variable number of arguments with arrow functions. Now let’s discuss Anonymous functions in JavaScript.
Anonymous Functions
An anonymous function is simply a function with no name. The purpose of using anonymous function is to perform a certain task and that task is no longer required to program. Generally, anonymous functions are declared dynamically at run time.
Anonymous functions are called only once in a program.Example:
// Working with an Anonymous function
var a = 10; // Global Scope Variable.
// creating a function(function() {
console.log("welcome to the world of Anonymous function");
var b = 20; // b is a local scope variable.
var c = a+b; // c is a local scope variable //a can be used because it is in the global scope
console.log("Addition of two numbers value is: "+c);})();
Output

This is the concept of anonymous functions. I think I explained it in a simple and easy way.
Higher Order Functions
A higher-order function is a function that takes functions as an argument or that returns another function as a result.
The best example of higher-order functions in Javascript is that of Array.map(), Array.reduce(), Array.filter().
Example 1: Array.map()
// working with Array.map()
let myNumberArray = [4,9,16,25,36,49];
let mySquareRootArray = myNumberArray.map(Math.sqrt);
console.log(mySquareRootArray);
Output

Example 2: Array.reduce()
// working with Array.reduce()
let someRandomNumbers = [24,1,23,78,93,47,86];
function getSum(total, num){ return total + num;}
let newReducedResult = someRandomNumbers.reduce(getSum);
console.log(newReducedResult);
Output

Example 3: Array.filter()
// Working with array filter
let ages = [12,24,43,57,18,90,43,36,92,11,3,4,8,9,9,15,16,14];
function rightToVote(age){ return age >= 18;}
let votersArray = ages.filter(rightToVote);
console.log(votersArray);
Output

Recursion
This is one of the key topics in functional programming. The process in which a function calls directly or indirectly is called a recursive function. This concept of recursion is quite useful in solving algorithmic problems like the Towers of Hanoi, Pre-Order, Post-Order, In-Order, and some graph traversal problems.
Example
Let’s discuss a famous example: finding the factorial of a number using recursion. This can be done by calling the function directly from the program repeatedly. The logic for the program is
factorial(n) = factorial(n) * factorial(n - 1) * factorial(n - 2) * factorial(n - 3) * ….. * factorial(n - n);// Finding the factorial of a number using Recursion
function factorial(num){ if(num == 0) return 1; else return num * factorial(num - 1);
}
// calling the function
console.log(factorial(3));
console.log(factorial(7));
console.log(factorial(0));
Output

Characteristics Of Functional Programming
The objective of any FP language is to mimic the use of mathematical concepts. However, the basic process of computation is different in functional programming. The major characteristics of functional programming are:
Data is immutable: The data which is present inside the functions are immutable. In Functional programming, we can easily create a new Data structure but we can’t modify the existing one.
Maintainability: Functional programming produces great maintainability for developers and programmers. We don’t need to worry about changes that are accidentally done outside the given function.
Modularity: This is one of the most important characteristics of functional programming. This helps us to break down a large project into simpler modules. These modules can be tested separately which helps you to reduce the time spent on unit testing and debugging.
Advantages Of Functional Programming
- It helps us to solve problems effectively in a simpler way.
- It improves modularity.
- It allows us to implement lambda calculus in our program to solve complex problems.
- Some programming languages support nested functions which improve maintainability of the code.
- It reduces complex problems into simple pieces.
- It improves the productivity of the developer.
- It helps us to debug the code quickly.
Disadvantages Of Functional Programming
- For beginners, it is difficult to understand. So it is not a beginner friendly paradigm approach for new programmers.
- Maintainance is difficult during the coding phase when the project size is large.
- Reusability in Functional programming is a tricky task for developers.
Conclusion
For some, it might be a completely new programming paradigm. I hope you will give it a chance in your programming journey. I think you’ll find your programs easier to read and debug.
This Functional programming concept might be tricky and tough for you. Even if you are a beginner, it will eventually become easier. Then you can enjoy the features of functional programming.
If you liked this article please share with your friends.
Hello busy people, I hope you had fun reading this post, and I hope you learned a lot here! This was my attempt to share what I’m learning.
I hope you saw something useful for you here. And see you next time!
Have fun! Keep learning new things and coding to solve problems.
Check out My Twitter, Github, and Facebook.