I was reading an article about functional programming where the writer states
(take 25 (squares-of (integers)))
Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.
Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?
Mod notice
This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.
Best Answer
Is it possible to implement such an example in Java without using destructive updates? Yes. However, as @Thiton and the article itself mentioned, it will be ugly (depending on one's taste). One way is using recursion; here's a Haskell example that does something similar:
Note 1) the lack of mutation, 2) the use of recursion, and 3) the lack of loops. The last point is very important -- functional languages don't need looping constructs built into the language, since recursion can be used for most (all?) cases where loops are used in Java. Here's a well-known series of papers showing how incredibly expressive function calls can be.
I found the article unsatisfying and would like to make a couple of additional points:
That article is a very poor and confusing explanation of functional programming and its benefits. I would strongly recommend other sources for learning about functional programming.
The most confusing part about the article is that it doesn't mention that there are two uses for assignment statements in Java (and most other mainstream languages):
binding a value to a name:
final int MAX_SIZE = 100;
destructive update:
int a = 3; a += 1; a++;
Functional programming eschews the second, but embraces the first (examples:
let
-expressions, function parameters, top-leveldefine
itions). This is a very important point to grasp, because otherwise the article just seems silly and might leave you wondering, what aretake
,squares-of
, andintegers
if not variables?In addition, the example is meaningless. It doesn't show the implementations of
take
,squares-of
, orintegers
. For all we know, they are implemented using mutable variables. As @Martin said, you can trivially write this example in Java.Once again, I would recommend avoiding this article and others like it if you really want to learn about functional programming. It seems to be written more with the goal of shocking and offending rather than teaching concepts and fundamentals. Instead, why not check out one of my all-time favorite papers, by John Hughes. Hughes tries to tackle some of the same issues that the article covered (although Hughes doesn't talk about concurrency/parallelization); here's a teaser: