In this post, I focus mainly on two aspects: higher order functions and lazy evaluation. As you know, it is impossible to cover all the aspects of functional programming in a few small blog posts. Consequently, I have decided to present some important features and let you explore the rest on your own. Once again, let us stick to Clojure.
Higher Order Functions:
If a function takes another function as an argument or it returns a function, then it is called a higher order function. In Java, it is impossible to pass a function as an argument to a function or to return a function as of now. We have to wrap the desired function either in an interface or in a class to make it work in Java. In Clojure, functions are first class members. What do we mean by that? Let us look at a couple of examples:
(map #(+ 3 %) [1 2 3 4 5])
The above returns (4 5 6 7 8). Simply, it has added 3 to every element of the vector.
Here is a filtering example:
(filter even? [1 2 3 4 5])
This returns, as you might have already suspected, (2 4).
Finally, consider this example:
(reduce + [1 2 3 4 5])
The above returns 15. It has added all the elements. Imagine how much code needs to be written in Java in order to accomplish these tasks.
We all know about this topic. However, is it possible for us to create an infinite sequence in Java? Obviously, Java compiler does not allow us. Look at the following code:
(def numbers (range 1000000000000))
With that, we have created a sequence ranging from 0 through 999999999999. Amazing! Here is one more example:
def fibonacci-numbers (auto-cat [1 1] (map + fibonacci-numbers (rest fibonacci-numbers))))
With the above, we have the infinite sequence of Fibonacci numbers. Yes, the some of the terms are not familiar to us but that does not matter. We can still appreciate the power of Clojure, a functional language.
Check out the following references:
A. Map, Reduce and Filter in Clojure « Tech behind Tech
B. Higher-order function
C. Whats the point of lazy-seq in clojure? - Stack Overflow
D. Lazy infinite sequences in Clojure and Python - Stack Overflow
Luncheon at Java Funfair
rpolavar 2700001DS8 625 Visits