Chapter 3
Functional Programming in Dart

Some of what makes JavaScript special is its support for functional programming. Since Dart aims to be familiar, let’s examine what it is like to program functionally in Dart.

We begin with the old standby, the Fibonacci sequence. In JavaScript, this might be written like so:

 
function​ fib(i) {
 
if​ (i < 2) ​return​ i;
 
return​ fib(i-2) + fib(i-1);
 
}

The Fibonacci sequence is a wonderful example for exploring the functional programming nature of a language since it, er, is a function but also because it demonstrates how to invoke a function because of its recursive nature.

I won’t bother describing recursion or the particulars of this function.[5] Instead, let’s focus on how to use the function in JavaScript.

 
fib(1) ​// => 1
 
fib(3) ​// => 2
 
fib(10) ​// => 55

So, JavaScript functions are simple enough. They are introduced with the function keyword, followed by the name of the function, the list of supported arguments in parentheses, and the block that describes the body of the function.

So, what would the equivalent Dart version look like?

functional_programming/fib.dart
 
// Dart
 
fib(i) {
 
if​ (i < 2) ​return​ i;
 
return​ fib(i-2) + fib(i-1);
 
}

Wait, how is that different from the JavaScript version?

 
function​ fib(i) {
 
if​ (i < 2) ​return​ i;
 
return​ fib(i-2) + fib(i-1);
 
}

Astute readers will note that the Dart version lacks the function keyword. Aside from that, the two function definitions are identical, as is invoking the two.

 
fib(1); ​// => 1
 
 
fib(5); ​// => 5
 
 
fib(10); ​// => 55

If nothing else, we can see that the designers of the Dart language have certainly succeeded in producing something familiar.

..................Content has been hidden....................

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