web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Jesús Almaraz blog / Functional Programming: Jav...

Functional Programming: JavaScript vs NAV (Part 1).

Jalmaraz Profile Picture Jalmaraz 669

Intro.

like learn another programming paradigms: JavaScript is a multi-paradigm language and allow us to understand functional programming.
Functional programming(FP) not about beauty of code, it´s about save money and time. It´s about reduce support efforts. First sight, FP seems to be something complex and plenty of limitations, but actually is a way to simplicity.

Objectives

Functional basic concepts.

Share state.

An object or variable that can be accessed out of a function, a global variable in a Codeunit. Must be avoided, mostly if it is a shared mutable state, the worst scenario. Hardest to detect errors in code are caused by global variables.

Pure function.

A pure function is a function that satisfies two conditions:
  • No side effects.
  • Referential transparency.

Side effects.

Side effects are:
  • Use of global variables.
  • Change input parameters. Only can change return value.
  • I/O operations (files, console, database).
  • Void functions: functions that don´t return any value.

Referential transparency.

A pure function always satisfies referential transparency: same input, same output. With the same input parameters always returns the same. How? Avoiding side effects and shared state (global scope variables).

Higher order function.

A high order function is a function that can receive another function as parameter or return a function.
Attention: I don´t mean the return value of a function this way: FunctionWithParameterInteger ( FuntionWithReturnInteger(X) ). This is another thing called function composition well known in every programming language. I mean a function itself:
function SomeOperationWithDecimal(TextMessageCaption,InputDecimal,ActionWithDecimal) {
    console.log(TextMessageCaption + ' of ' + InputDecimal + ' is '
    + ActionWithDecimal(InputDecimal));
}
SomeOperationWithDecimal("Square rooth",4,Math.sqrt);
SomeOperationWithDecimal("Absolute",-4,Math.abs);
Result:

Square rooth of 4 is 2
Absolute of -4 is 4
 
We can see in the picture a new function SomeOperationWithDecimal with three input parameters: TextMessageCaption, InputDecimal and attention ActionWithDecimal. Attention because this last parameter is a function, a function that will be applied inside, not the return value of a function. In the example we can see how SomeOperationWithDecimal is called first with function Math.sqrt and later with Math.abs as third parameter. In JavaScript, functions are really powerful. This is not available in NAV.

Loop avoiding.

Loops are unsafe and must be avoided. Functional languages have a tool to do it: Functor objects.
A functor object have some methods like map, filter or reduce, that apply a function to all its members.
var PrintDouble = function(DecValue) {console.log(DecValue*2)};
ArrayDeDecimales = [2,3,4,5];
ArrayDeDecimales.map(PrintDouble);
The console:

4
6
8
10
 
 Array.Map sentence, with a function equals for each member of Array do this action. This is the way functional languages avoid loops. Another way is recursion.

Declarative vs imperative.

FP style put expressions and definitions over statements, what to do over how to do. Separate declarations and implementations. Also, JavaScript has an elegant way to define functions (input value => return value):
var GetDouble = NumberInput=>NumberInput*2;
console.log(GetDouble(2));

Immutability.

Once you create an object or variable its value or state never change. If you need to make a change you must create another derived object with the change, but keep original object as it was. Could sound strange, but in NAV we are doing it many years ago. Immutability allows you multi-thread, is more simple, expressive and safer. I haven´t understood this until I found  good NAV examples of this, and then all made sense.

Finally……..the definition!!!

In computer science, functional programming is a programming paradigm (a style of building the structure and elements of computer programs) that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
As definition of an expressive way of programming, this is not very expressive!!! Think this is much better (https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0):
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. Functional programming is declarative rather than imperative.

Another concept: Clousure.

I left to the end this last concept, because not applicable to non-functional languages and most people may not be interested, but I think this concept show how much important are functions in JavaScript. We can do this with a Function in JavaScript:
var SalutationBeforeClousure = function(SalutationFormula,PersonName) {   
        return SalutationFormula + ' ' + PersonName + ':';
    };
var Salutation = function(SalutationFormula,PersonName) {
    return function(PersonName){
        return SalutationFormula + ' ' + PersonName + ':'};
    };
 
console.log(SalutationBeforeClousure("Hello","David"));
 
var SalutationWithDearMr = Salutation('Dear Mr.');
console.log(SalutationWithDearMr('Jon Jones'));
console.log(SalutationWithDearMr('Daniel Cormier'));
 
Console result:
Hello David:
Dear Mr. Jon Jones:
Dear Mr. Daniel Cormier:
Function salutation takes two arguments and returns a function with second input value. We can´t execute this function passing two parameters once. Instead we do:
  • Pass first parameter and function keep frozen waiting for second one.
  • Pass second parameter and then the inside function is executed.
The power of all this is to create functions derived from others: we created a function SalutationWithDearMr from Salutation where the salutation formula always is Dear Mr. and only takes the person name.
There is another related concept, currying: convert a multi-parameter function in a unary function (only one parameter), called by steps, with this technique. We transform a binary (two parameters) function SalutationBeforeClousure in a unary function called twice, once for each parameter. Advantage? Create new functions from others. Functions become powerful objects this way.

Final.

Next post we could see how to apply (part of) these concepts in non-functional languages, as AL. About programming paradigms, is important to separate what is useful and not for our own requirements. This is about to be pragmatic vs dogmatic, and if we want to apply FP, we have to be very pragmatic and make some adaptations in functional programming paradigm.

Comments

*This post is locked for comments