Functional Programming IN NON-FUNCTIONAL LANGUAGES
What is functional programming? In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.[1] Functional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate computability, the Entscheidungsproblem, function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus. – Wikipedia: Functional programming (
TL;DR – Give me the Cliffs Notes First-class functions Functions are not treated any different than any other named thing Can be passed as argument and returned as a result Pure functions No side effects Results are constant given the same input Evaluation is always thread safe and order is never important Recursion looping is often done via recursion Recursion is safe and optimized by the compiler Type system Types are inferred Data always has a type Pattern matching on complex types
But I can’t/don’t/won’t use a functional language What should I use to get started? Java -> Scala .NET -> F# JavaScript Use the principles of functional programming in non-functional languages
The principles Don’t make setters in your class definitions – instead, make your fields constant and defined in the constructor. Then you can expose them as public. Avoid side effects. Treat your memory as immutable. Always make pure functions - Your function is like a math function. It doesn’t care about the state of the environment. Given the same input, it always produces the same output. Everything it needs is passed in. Many languages have implemented some functional principles although the syntax remains imperative Java 8 will support lambda expressions – anonymous functions JavaScript, PHP 5.3, VB 9, C# 3, C++ 11 have first-class functions, lambda expressions JavaScript has a functional, expressive syntax Asynchronous for-each loops
Questions?