Tuesday, February 2, 2016

Functional Programming in PHP on Leanpub

Functional Programming in what?? Yes, PHP. While far away from being a pure functional programming language, the newer releases of PHP (5.3+) have incorporated enough features that enable you to use it functionally.
"OO in the large, functional in the small"
So they say,  I think PHP can be used in a compelling fashion to create more testable and easy to reason about code. You can write functional code embedded within the domain or services of any MVC framework of choice. I've began this long project in Leanpub, so it's free to read.

Hope you enjoy it! 

Tuesday, December 22, 2015

Understanding Lambda Expressions

Lambda expressions (or lambda functions) are essentially blocks of code that can be assigned to variables, passed as an argument, or returned from a function call, in languages that support high-order (first-class) functions. They have been part of programming languages for quite some time. Some examples include Smalltalk, Lisp, Ruby, Scala, Python, and, more recently, Java and JavaScript. Here are some examples: 


square = lambda x: x**2

square(6) //->; 36


square = lambda { |x| x * x }
square.(6) #-> 36 

JavaScript (fat-arrow functions): 

var square = x => x * x;
square(6) //-> 36

Lambda expressions are also known as closures or blocks. If you look closely at the Ruby code, you can see the declaration of a “callable” block of code (encapsulated in { } braces) that is assigned to a variable and run. Lambda expressions are also called closures because they access state from its surrounding lexical scope. This is unlike function pointers in C, which can also be passed around but do not carry (or close over) their lexical scope.

Most people people perceive lambdas simply as an anonymous function, but when you study them closer (perhaps from a functional programming point of view), lambda expressions carry a lot more meaning and are a lot more powerful than you think. To speak about this more concretely, I’ll refer to JavaScript’s “arrow” syntax shown above.


The most notorious difference is in syntax. Lambda expressions offer a syntactical advantage of over a traditional anonymous function declaration

function (x) { return x * x };

by removing a few artifacts like the function and return keywords, which makes these expressions feel more like just callable blocks of code. This syntax also makes your code a lot more succinct when used in conjunction with high-order functions like map, reduce, and filter:

range(1, 5).map(x => x * x); //-> [1, 4, 9, 16, 25]


The benefits of using lambda expressions extend way beyond just syntax. Lambdas encourage you to practice the first of the famous SOLID principles of software design: Single Responsibility. Applied to functions, single responsibility just means that functions should have a single purpose. While you can have lambda expressions contain multiple statements

(x, y) => {
  // do something with x and y  
  // statement 1 
  // statement 2   
  return result;

most of its usage derives from being inlined as a function argument into larger expressions. This means that you can create several small lambda functions that do exactly one thing, and combine them together to form whole programs:

range(1, 5)
   .filter(x => (x % 2) === 0)
   .map(x => x * x); //-> [4, 16]

But to really understand why they are so important, we need to examine lambda expressions from a functional programming point of view. 

Pure Functions

Functional programming treats functions as pure mathematical relations or mappings between sets of types; in this case the set of inputs (domain) and output (range or codomain). Hence, you can view any functions as a mapping of types. For instance, the squared function is a mapping from Number to Number

You can also map into any types, including user-defined types like a Long number to an Account object:

As you can see from these diagrams, mathematically speaking, a functions output must be solely derived from its input and not from any other state outside of the function’s scope. This absence of side effects is what determines that a functions is pure, as all functions in FP should be. Lambda expressions encode this pretty well into its syntax by using the logical implies symbol “=>” to mean that a set of inputs implies a certain output

Referential Transparency

We can extend this concept of purity to a mathematical principle called referential transparency, which means that a pure function can always be substituted for its computable value without altering the meaning of an expression. For a concrete example, consider a pure function like sum:

var size = (arr) => !arr ? 0 : arr.length;

And a function average

var average = (arr) => Math.round(sum(arr) / size(arr))

For an input such as [80, 90, 100], size will consistently return the value 3. Because this function always returns the same output on the same input, it’s said to be referentially transparent — actually the entire program above is. That means that I can use size(arr) interchangeably with the value 3 in the expression above, without altering its meaning. This mathematical quality makes our programs much easier to reason about and easier to trace on any given input. Indeed, these are very simple functions yet the concepts apply equally as well to the most complex algorithms. Referential transparency means that I can treat functions truly as black-boxes because I can predict a function’s outcome based solely on the input provided. 

Consequently, it’s easy to see that under referential transparency there’s no room for either no-argument functions or void functions; mathematically speaking, either of these cases implies the empty set “∅” in the domain or codomain, respectively. Take the following example that uses the empty set notation in place of the arguments list: 

var hello = () => console.log('Hello!');

Zero-arity functions or void functions always imply that side effects are taking place, since no other real work could be done without accessing resources outside of its own scope. Lambda expressions reveal this mapping more closely. 


All of these principles serve an important purpose: to facilitate function composition — the epitome of functional programming. Composition is used to orchestrate the execution of functions in a loosely coupled manner where the output of one is used as the input to the next. 

f o g (x) = f(g(x))

At a fine-grained level, function composition resembles the “coding to interfaces” principle because it treats functions as a black boxes with clear inputs and outputs. For example: 

var str = 'We can only see a short distance
           ahead but we can see plenty there
           that needs to be done';
var explode = str => str.split(/\s+/);
var size = arr => !arr ? 0 : arr.length;
var countWords = compose(size, explode);
countWords(str); //-> 19

I can use composition to join independent functions and create entire programs based on these simple concepts. Lambda expressions encourage us to create programs that are declarative,  modular, and reusable at a very fine-grained level!

    Saturday, September 26, 2015

    JavaScript through the Lenses of Functional Programming


    One of the main challenges of large-scale application development, especially with JavaScript,  is keeping track of the state of the system at any point in time. We create lots of objects and pass them around to functions that are free to mutate them as they please and, most often, this makes it incredibly difficult to find and hunt down bugs.

    For this reason, functional programming is on the rise, as evidenced by the recent adoption of hybrid OO/FP languages like Scala, F#, and JavaScript. It favors object immutability and elimination of side effects in your code, compared to procedural an object-oriented  programming that are based on mutations and side effects. However, immutability is hard to grok for most people. Can you imagine not being able to modify objects once they've been created?

    Actually, yes. If you think of the way mathematical systems work, they can carry out the most complex algorithms without ever mutating values. In other words, if you pass x to a Math.square function, you would never expect the original variable x to change, would you? This same reasoning that we apply to numbers and maths, we can also apply it to programs, but for this we need to be a bit more disciplined. JavaScript's primitive types are already immutable, but this is not the case for user-defined types, like Person:

    To this object, I can modify all of its data and behavior. To make this object immutable, JavaScript has an Object.freeze function, which augments its internal properties (Writable and Configurable) so that user code can't mess with the object's internal state. You can also encapsulate state under functions with Immediately Invoked Function Expressions (IIFE). Consider this simple type Money:

    You can safely pass Money objects around without having to worry about its internal state being altered unexpectedly. Money has Value Object semantics that hide its internal state behind an object literal. These are some of hoops we can jump through to ensure your state is preserved as you expect it to be, which will make your code easier to trace and debug. 

    However, the need to set or modify an object's properties after it's been created is very strong and occurs very frequently. What can we do? 

    Immutability with getters and setters

    Applying functional programming to your application is not restricting all mutation, but eliminating observable changes outside of your function scope; so that executing a function leaves the system in exactly the same state as it found it. Hence, functional programs are stateless. This statement has large implications, but in the context of object creation and modification, we need to ensure that setting an object's properties does not alter it. One way of doing it is by returning new copies of the object, as so:

    But because you're responsible for keeping and sharing that state, this opens the door to writing very tedious code. Lenses automate this for us, so that you can modify the state of any object in an immutable fashion. Using JavaScript's functional library Ramda.js, I can write the following code:

    At first glance, this might not seem like a big deal, but fact is that the call to R.set(), which is used to modify one of the object's properties, actually copies the state of the original object and returns a brand new object olivia with the modified property, keeping the original intact. Ramda does this by first performing a deep copy of the object using R.clone.

    Composition with Lenses

    Because Ramda's implementation of lens functions are curried, they can be easily used in compositions. As shown in the following example: 

    Another main cause of bugs resulting from mutations is when a developers forgets about JavaScript's pass-by-reference. In this scheme, a function has complete control over the contents of an array argument:

    This code causes a side effect on the provided array reference, since running the function effectively changes the content of the array declared outside of its scope. If you want to avoid this inadvertent side effect, you can use lenses: 

    Wrap up

    With lenses any operation on objects or arrays is immutable! This means you can be sure to pass any object wrapped in a lens into a function, and the original will never inadvertently change; thus, obeying the central principles of functional: total elimination of externally observable mutations and side effects!

    For more detailed information on this topic, you can buy my book. 



    1. http://ramdajs.com/0.17/docs/#lens

    Wednesday, July 1, 2015

    Thorough Introduction to Functional JavaScript Programming


    The rapid pace of web platforms, the evolution of browsers, and, most importantly, the demand of your end users has had a profound effect in the way we design web applications today. Users demand web applications feel more like a native desktop or mobile app so that they can interact with rich and responsive widgets, which forces JavaScript developers to think more broadly about the solution domain push for adequate programming paradigms.

    With the advent of Single Page Architecture (SPA) applications, JavaScript developers began jumping into object-oriented design. Then, we realized embedding business logic into the client side is synonymous with very complex JavaScript applications, which can get messy and unwieldy very quickly if not done with proper design and techniques. As a result, you easily accumulate lots of entropy in your code, which in turn makes your application harder write, test, and maintain. Enter Functional Programming.

    Functional programming is a software methodology that emphasizes the evaluation of functions to create code that is clean, modular, testable, and succinct. The goal is to abstract operations on the data with functions in order to avoid side effects and reduce mutation of state in your application. However, thinking functionally is radically different from thinking in object-oriented terms. So, how do you become functional? How do you begin to think functionally? Functional programming is actually very intuitive once you’ve grasped its essence. Unlearning old habits is actually the hardest part as it can be a huge paradigm shift for most people that come from an object-oriented background. Let’s convert a simple imperative “Hello World” program written in JavaScript, to functional:



    These smaller functions combine to implement a program that is easier to reason about as a whole. Why does the functional solution look this way? I like to think of it as basically parameterizing your code so that you can easily change it in a non-invasive manner. This is due to functional programming’s inherent declarative mode of development. Imperative programming tells the computer, in great detail, how to perform a certain task.             

    Declarative programming, on the other hand, separates program description from evaluation. It focuses on the use of expressions to describe what the logic of a program is without necessarily specifying its control flow or state changes.

    This programming style is possible in JavaScript because of its support for first-class, high-order functions, which is a simple way of defining a function that accepts other functions as parameters or whose return value is a function.

    While adopting a declarative style can be beneficial, sometimes you might find that functional code can be a bit harder write; this is a natural first impression before unlearning old methods and habits, as well as becoming comfortable with a higher level of abstraction or expressiveness. So why do it? The remarkable quality of declarative programs is that you wind up writing fewer lines of code and, simultaneously, get more work done. Consider this example: Write a short program to find the longest name in a collection of names. Your first approach is to write something like:

    This imperative approach manually iterates over the array from start to finish and keeps track of the longest state name as I iterate. Functional programming takes a different approach by raising the level of abstraction in your code and yielding most of the work to the most robust and optimized artifact in your application, your language runtime, without having to loop at all using recursion. Let’s use it to refactor the same program:

    Why go through so much effort to eradicate loops from our code? Loops imply code that is constantly changing or mutating in response to new iterations. Functional programs aim for statelessness and immutability as much as possible so that after a section of code runs no existing variables are changed. To achieve this, functional programming makes use of functions that avoid side effects and changes of state—also known as pure functions.

    Pure Functions

    Functional programming is based on the premise that you will build immutable programs solely based on pure functions. A pure function has the following qualities:

    • Depends only on the input provided and not on any hidden or external state that may change as a function’s evaluation proceeds or between function calls.
    • Does not inflict changes beyond its scope, like modifying a global object or a parameter reference.

    Pure functions can be very hard to use in a world full of dynamic behavior and mutation. But, practical functional programming doesn’t restrict absolutely all state changes; it just provides a framework to help you manage and reduce, while allowing you separate the pure from the impure. It’s more critical to ensure no externally visible side effects occur—immutability from the application’s point of view.

    Functions with side effects are, generally, bad design because they rely on data outside of the local scope of the function call, making it difficult to determine exactly what a function is supposed to do when they are run. Pure functions, on the other hand, have clear contracts as part of their signatures that describes clearly all of the function’s formal parameters, making them simpler to understand.
    Consider the example of fetching for processing a payment for student given their SSN. Let’s model this with three side effect free functions.

      Composing all three functions makes up our processPayment function:

        Removing all practical side effects made our programs less brittle to changing external conditions. Making a function’s result consistent and predicable is a trait of pure functions called referential transparency.

        Referential transparency and substitutability

        Referential transparency is a more formal way of defining a pure function. Purity in this sense refers to the existence of a pure mapping between a function’s arguments and its return value. Hence, if a function consistently yields the same result on the same input, it is said to be referentially transparent. Here’s a quick example:

        This function always returns the same output when provided the same input. If this were not the case, it must mean that that the function’s return value is being influenced by some external factor. This quality of referential transparency is inherited from mathematical functions, which state that a function is a pure relation between inputs and outputs with the property that each input yields exactly one output.

        Let’s tackle a more complex example: adding a new grade to a list and compute its average. I will create two functions append and average:

        Putting it all together:

        This function yields a consistent result based only on the provided input and does not cause any side effects to the grades list after returning. Referential transparency is a very important quality of pure functions as it allows functional languages to optimize function calls, as you’ll see later in this post.

        Furthermore, a corollary of referential transparency is the principle of substitutability. Because the result of a referentially transparent functions consistently depends only on the values of the arguments provided to it, we say that a function’s return value can be directly replaced into an expression without changing its meaning. Math operators behave this way: adding 2 + 3 can be substituted with 5 into any equation and the result of the equation will forever remain the same. The following statements are all equivalent:

        (2 + 3) * 8 === (5) * 8 === 40

        The same expectations we hold for mathematical operators should also apply to pure functions as well. Now that you’ve caught a glimpse at the fundamental principles behind functional programming, perhaps its definition is more tractable now. So what is functional programming?

        Functional programming refers to the declarative evaluation of pure functions to create immutable programs by avoiding externally observable side effects.

        Becoming functional
        In order to become functional, you must learn to think functionally and have the proper tools to develop your functional awareness—the instinct of looking at problems as a combination of simple functions that together provide a whole solution. Functional programming is a software paradigm that, while based on very foundational concepts, will completely shift the way you think about a problem.

        Modularizing your code
        At a high level, functional programming is effectively the interplay between decomposition (breaking programs into small pieces) and composition (joining pieces to make programs). It is this duality that makes functional programs modular. As I mentioned previously, the unit of modularity, or “unit of work” is the function. Thinking functionally typically begins with decomposition by learning to break up a particular task into logical subtasks (functions):

        If need be, these can be decomposed further until arriving at simple, pure functions, each of which is an independent unit of work. Modularization in functional programming is closely related to the singularity principle, which states that functions should have a single purpose, which is exactly what I was able to achieve.

        Functional composition can be understood simply as taking the output of one function and plugging it into the next. The result of composing two functions together is another function that gets called with the actual arguments. Remember this from school?

        f . g = f(g(x))

        Its back! It reads: “f composed of g,” which supposes a type-safe relationship between what g returns and f receives. As seen in our previous example:

        Behind the scenes, the new roster array returned from append will be passed into calcAverage:
        Given a class roster array with students Haskell, Rosser, and Church with grades 97, 82, 100, respectively, if Alan Turing’s grade in the class was a 75, the new average will be:

        The concept of pure functions transitively applies to computeAverageGrade. Because it was built from the composition of two pure functions, it is itself pure. Understanding compose is crucial for learning how to implementing modularity and reusability in functional applications, as it leads to code where the meaning of the entire expression can be understood from the meaning of its individual pieces, a quality that becomes very hard to achieve in other paradigms. Also, it raises the level of abstraction so that you can clearly outline all of the steps performed in this code without being exposed to any of its underlying details. Because the compose function accepts other functions as arguments, it is known as a high-order function, a artifact in functional languages.
        Functional programming not only makes your code more modular, but in some cases it can also speed up the evaluation of your functions.

        Optimizing your function calls
        Functional programming will not speed up the evaluation times of your individual functions; rather, its strategy is based on avoiding duplicated function calls, which can potentially speed up your application overall. This technique is called memoization, which originates from the premise of functions being referentially transparent. Recall that referentially transparent functions always return the same value on same inputs. Through memoization the set of input parameters are encoded as a string or number and used as the cache key to a function’s result, internally persisted and looked up when the function is invoked again on the same input.

        Consider a function that computes a secure hash based on a user’s password. Depending on the type of algorithm used, this function can be very expensive to call. Generally, with secure encryption the more intense the algorithm the stronger the hash will be. Caching these results can be a tremendous improvement.

        Calling generateSecureHash again on this same input bypasses the computation and returns the memoized result. The effectiveness of memoization is directly proportional to the level modularity in your code. As you decompose big tasks into a greater number of smaller, single-purpose functions, memoization can be used more efficiently to achieve a higher level of fine-grained caching and optimization.

        Memoization is not a native JavaScript feature, but one way to install it is with API code by augmenting JavaScript’s extensible Function object. You can also have it as a standalone call.

        The beauty of this level of caching in functional languages like JavaScript is that it can be implemented without adding any boilerplate code of placing cache checks and inserts all over your functions.

        While on the topic of writing boilerplate code, consider null checks. Handling errors and null values generally leads to an explosion of if-else conditions in your code. This excessive use of branching logic creates code that is hard to maintain and test. As an example, suppose I need to extract the country name of a student’s school address. I think we’ve all seen similar convoluted code before:

        This anti-pattern of clean design is addressed with functional data types called monads used for null-safe operations as well as high-level abstractions that will allow you to write more robust, extensible code while handling errors effectively.

        Handling errors fluently using Monads
        Functional programming places a clear distinction between pure error handling and exception handling. Our goal is to implement pure error handling as much as possible, and allow exceptions to fire in truly exceptional conditions, just as the ones described earlier.

        I will use a purely functional data type called monads to order to treat potentially hazardous state as safe, encapsulated values that use high-order functions to abstract out and consolidate error-handling logic and defensive null-checks. By returning consistent, predictable values, referential transparency is preserved across function calls and error-bearing expressions can easily be combined in a very fluent manner.

        This is possible using the Maybe monad. Maybe is a data type that implements a very intuitive concept: a value is maybe there, maybe not. When wrapping a potentially unsafe value, Maybe either returns an object containing the value or an object containing “nothing.” Instead of returning unsafe null values that then you’ll have to check for, let’s show getCountry based on Maybe.

        Building extensible code with function chains
        Let’s tackle a different problem. Suppose you are tasked to write a program that would compute the average grade of students that have enrolled in more than one class. Approaching this problem from a functional mindset, you can identify three major steps:
        •  Selecting the proper set of students (whose enrollment is greater than one)
        • Extracting their grades
        • Calculating their average grade

          So far you’ve seen how functional programming can help us create modular, testable, and extensible applications. So, how does all this fare when running in a browser environment?

          Streamline client-side development
          Client side events come in many flavors: mouse clicks, text field changes, focus changes, etc. Consider the scenario of handling value changes on a text field and using the value entered to update a welcome banner. Naturally, as any JavaScript developer would do, I resort to jQuery:

          Arguably, this code is not very modular, as I am required to implement the logic of dealing with user input and updating the banner into a single function. Rather, the functional approach to handling events is to subscribe to asynchronous streams and, in a similar fashion to traversing an infinite collection of items, be able to compose a series of functions onto any event instance in a way that is separated from the actual browser event handling logic. In addition, I want to be able to port the concepts of referential transparency and immutability. Client side developing in functional is done reactive with Functional Reactive Programming (FRP). 

          FRP is the combination of reactive programming, or programming with data streams, with a strong focus on composition. For this I can leverage a functional library called Bacon.js that enhances JQuery’s API to define the asEventStream function that works with asynchronous data streams. For example, to subscribe to all keyup events on an input field, I can write the following code:

            Here’s where the functional programming comes in. The onKeyUp function is like an event bus that can treat events as if they were elements in a collection, which means I can easily map functions onto it to immutably manipulate the target objects. I will create a function to extract and run logic on the value in the event stream. Calling the toProperty method on the stream creates a value accessor on any keyup events that occur on that HTML field, which I can listen for and handle within the onValue method. 
            Now, I pose to you the same questions with which we started the section: Is this program: Modular? Testable? Extensible? Readable? Maintainable? Functional programming is a paradigm shift that can drastically transform the way in which you tackle solutions to any programming challenges. So, is functional programming a replacement for the more popular object-oriented design? Fortunately, applying functional programming to your code is not an “all or nothing” approach.

            In fact, lots of applications can benefit from it when used alongside an object-oriented architecture. Due to rigid control for immutability and shared state, functional programming is also known for making multi-threaded programming more straightforward. Because JavaScript is a single-threaded platform, this is not something we’ll need to worry about or cover in this post.

            In sum, client-side applications are becoming more and more complex every day and, if done poorly, can become a nightmare for companies to maintain. Some companies actually enforce the use of certain paradigms and coding styles, others don’t and welcome the investment of time to learn new and better ways to accomplish certain tasks. Hybrid languages like JavaScript become really useful in these cases as they allow developers to experiment with a mix of styles. Whichever your situation is, I truly believe getting familiar with functional programming, even if you had no immediate plans to move into it, can truly enhance your skills and your ability to tackle complex problems in a way not possible using conventional methods.

            If you liked this article and topic and want to read about it more in-depth, please order my book.