Introduction to functional programming

We briefly discussed functional programming and F# in Chapter 1, Getting Started. In the F# primer section, we said that functional programming treats programs as mathematical expressions and evaluates expressions. It focuses on functions and constants, which don't change like variables and states. Functional programming solves complex problems with simple code; it is a very efficient programming technique for writing bug-free applications; for example, the null exception can be avoided using this technique.

Functional programming is language-agnostic, which means it is not language-specific. Functional programming focuses on a structured approach; it doesn't have multiple entry and exit points. It doesn't have goto statements, so it is easy to create small modules and create large modules using small blocks of structured code (or in other words sub-modules), which increases the re-usability of code. One function can be used as the input of another function and that function can output a new function.

Here are some rules which make it easy for us to understand functional programming:

  • In functional programming, a function's output never gets affected by outside code changes and the function always gives the same result for the same parameters. This gives us confidence in the function's behavior that it will give the expected result in all the scenarios, and this is helpful for multithread or parallel programming.
  • In functional programming, variables are immutable, which means we cannot modify a variable once it is initialized, so it is easy to determine the value of a variable at any given point at program runtime.
  • Functional programming works on referential transparency, which means it doesn't use assignment statements in a function. For example, if a function is assigning a new value to a variable such as shown here:
Public int sum(x)
{
x = x + 20 ;
return x;
}

This is changing the value of x, but if we write it as shown here:

Public int sum(x)
{
return x + 20 ;
}

This is not changing the variable value and the function returns the same result.

  • Functional programming uses recursion for looping. A recursive function calls itself and runs till the condition is satisfied.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.137.164