What is referential transparency in functional programming and what are its main benefits?

The definition of functional programming is quite easy. Functional programming is the programming with mathematical functions. Is that all? Of course, not!
Functional programming is the programming with mathematical functions. I think, you already guess it. The key to this definition is the expression mathematical function. Mathematical functions are functions that return every time the same result when given the same arguments. They behave like an infinite big lookup table.
The property, that a function (expression) always returns the same result when given the same arguments, is called referential transparency. Referential transparency has far reaching consequences:
- Mathematical functions can not have a side effect and can therefore not change the state outside the function body.
- The function call can be replaced with its result, but can also be reordered or put on a different thread.
- The program flow is defined by the data dependencies and not by the sequence of instructions.
- Mathematical functions are a lot easier to refactor and to test because you can reason about the function in isolation.
That sounds very promising. But which so many advantages, there is a massive restriction. Mathematical functions can not talk to the outside world. Examples?
Mathematical functions can't
- get user input or read from files.
- write to the console of into a file.
- return random numbers or time, because the return values are different.
- build a state.
Thanks to mathematical functions, the definition of functional is very concise but helps not so much. The key question still remains. How can you program something useful with functional programming? Mathematical functions are like islands that have no communication with the outside world. Or to say it in the words of Simon Peyton Jones, one of the fathers of Haskell. The only effect that mathematical functions can have is to warm up your room.
Now I will be a little bit more elaborated. What are the characteristics of functional programming languages?
Characteristics of functional programming languages
Haskell will help me a lot on my tour through the characteristics of functional programming.
There are two reasons for using Haskell.
- Haskell is a pure functional programming language and therefore you can study very well the characteristics of functional programming by using Haskell.
- Haskell may be the most influential programming language of the last 10 - 15 years.
My second statement needs a proof. I will provide them in the next post for Python and in particular C++. Therefore, a few words about Java, Scala, and C#.

In particular, a function can not set state. This is a very different way of thinking from imperative languages such as Java, where there are objects all over the place with state that gets changed by method calls.
Referential transparency is a phrase from the functional programming world which means, basically, "no side effects". Side effects include reading any state which is not passed in as an argument or setting any state which is not part of what is passed back as an argument. If a function is referentially transparent, then a call to that function with a specific set of values as arguments will always return exactly the same value.
When functions are composed into larger functions, it is easier to reason about them when they are referentially transparent and there are no side effects to worry about. Of course, in the real world it can be very useful to be able to store some state data, so how does one implement this functionality in a pure functional language?
The answer is Monads. This is described pretty well in a 1992 paper by Philip Wadler called "Monads for functional programming". Reading this paper helped me understand the motivation for monads. Monads provide a way to collect all those side effects into known locations in the program. When all of the side effects are collected into monads, the rest of the program (all of the non-monad parts) are still referentially transparent, so remain easier to compose. The side effects are still there, but because they are encapsulated by the monads, it is easier to deal with them.
Group TheoryWhen you read about monads, at some point you will come across a mention of Category Theory as the source of monads. Category Theory is pretty abstract, and you don't need to know it to understand monads. But monads are a mathematical concept, so digging into the math background of the concept could help solidify your understanding.
After reading a bunch of stuff about Category Theory, I went back to Group Theory, which for our purposes you can think of as a special case of Category Theory. While reviewing groups, rings and fields, I stumbled across monoids, a term which I had not recalled from my readings in the field years ago. It's not quite the same thing as a monad, but because Group Theory is focused on transformations, I started thinking of monads as transformations, which I think helped my understanding of them.

Those tenets will be the subject of my email course:
- Functions are pure
- Functions use immutable data
- Functions guarantee referential transparency
- Functions are first-class entities
After that, I’ll briefly touch on how functional programming applies these tenets to encourage us to think carefully about our data and the functions that interact with it.
By the end, you’ll be able to understand how this approach leads to code that is:
- Easier to understand (that is, “expressive”)
- Easier to reuse
- Easier to test
- Easier to maintain
- Easier to refactor
- Easier to optimize
- Easier to reason about
Sound exciting? If so, you'll love the new e-book. ?
The e-book will be released on December 13th. You can pre-order the e-book now for just $49! And as special offer to the free FreeCodeCamp community, I am offering $10 off with the discount code "freecodecamp".
See you in there! ??✍

What is Functional Programming?
Firstly, Functional programming is a programming paradigm in which everything is bound using pure mathematical functions. It’s a declarative programming approach. In contrast to an imperative style, which focuses on “how to solve,” it focuses on “what to solve.” Instead of statements, it uses expressions. A statement is executed to assign variables, but an expression is evaluated to create a value. In addition, Those functions have some unique characteristics.
Components of functional programming
- Pure functions
- Referential transparency
- Functions are First-Class and can be Higher-Order
What is a Pure Function?
Pure functions are normal functions with some characteristics :
- Total / Not Partial
- No Randomness
- No Side Effects
- Not Null
- No Exception
- No Mutation
Example of Pure Function
def add(a: Int, b: Int): Int = a + b
Example of Not a Pure Function
def divide(a: Int, b: Int): Int = a / b
The ‘divide’ function passes all the parameters of being a pure function but if in case ‘a’ will be divided by 0, Then it will throw an exception which will make it not a pure function.
Advantages and disadvantages of Functional Programming
- This programming aids in the effective resolution of difficulties.
- It improves modularity.
- It allows us to implement lambda calculus in order to solve complex problems
- Some programming languages support nested functions so it improves the maintainability of the code
- It reduces complex problems into simple pieces so that it will be easy to solve.
- It’s difficult to grasp for novices, hence it’s not a beginner-friendly paradigm approach for new programmers.
- Maintenance is difficult during the coding phase when the project size is large
- Moreover, Reusability in Functional programming is a tricky task for developers
For further information on functional programming wait for the next blog…
For more details please visit: https://en.wikipedia.org/wiki/Functional_programming

functional programming definition programming
(FP) A program in a functional language consists of a set of (possibly recursive
definitions and an expression whose value is output as the program's result. Functional languages are one kind of declarative language
. They are mostly based on the typed lambda-calculus
with constants. There are no side-effects
to expression evaluation so an expression, e.g. a function applied to certain arguments, will always evaluate to the same value (if its evaluation terminates). Furthermore, an expression can always be replaced by its value without changing the overall result (referential transparency
The order of evaluation of subexpressions is determined by the language's evaluation strategy
. In a strict
) language this will specify that arguments are evaluated before applying a function whereas in a non-strict (call-by-name
) language arguments are passed unevaluated.
Programs written in a functional language are generally compact and elegant, but have tended, until recently, to run slowly and require a lot of memory.
Examples of purely functional languages are Clean
, and SML
. Many other languages such as Lisp
have a subset which is purely functional but also contain non-functional constructs.
See also lazy evaluation
Lecture notes (ftp://ftp.cs.olemiss.edu/pub/tech-reports/umcis-1995-01.ps). or the same in dvi-format (ftp://ftp.cs.olemiss.edu/pub/tech-reports/umcis-1995-01.dvi).
SEL-HPC Article Archive (http://lpac.ac.uk/SEL-HPC/Articles/).

Message passing, techniques for communication between objects makes the interface descriptions with external systems much simpler. Software complexity can be easily managed. OOP is popular in large software projects because objects or groups of objects can be divided among teams and develop in parallel and it seems to provide a more manageable foundation for larger software projects.
# Functional Programming :- Functional language programs contains no assignments statements, so variables, once given a value, never change. Functional programs contain no side-effects at all. A function call can have no side effect other than to compute its result. This eliminates major source of bugs, and also makes the order of execution irrelevant, since no side effect can change the value of an expression, ti can be evaluated at any time. This relives the programmer of the burden of prescribing the flow of control. Since expression can be evaluated at any time, one can freely replace variables by their values and vice-versa that is, programs are "referentialy transparent". This freedom helps makes functional programs more tractable mathematically then their conventional counterparts. The time it takes to develop code, and even more importantly, to modify program is substantially faster for functional programs than for procedural programs. This is important for prototyping and carrying out exploratory research. Mathematics's functional programming constructs Map and Apply allow you to do many things in one line that would normally take several loops in other languages. If a functional program doesn't behave the way you expect it to, debugging it is a breeze you will always be able to reproduce your problem because a bug in a functional program doesn't depend on unrelated code paths that were executed before it. A functional program is ready for concurrency without any further modification you never have to worry about dead-blocks and race conditions because you don't need to use locks. In a functional program all states are stored on a stack in the arguments passed to functions. This makes hot deployment significantly easier. An uninteresting property of functional language is that they can be reasoned about mathematically. Since a functional languages is simply an implementation of a formal system, all mathematical operations that could be done on paper still apply to the programs written in that language.
Storage Management in Programming Language
Programming Languages Concepts
Subprogram Sequence Control in Programming language.
Structured Sequence Control in Programmig language
Sequence Control with in Statements
Implicit and Explicit sequence Control
Difference between C language and C++ language.

I love a lot of the thinking in functional programming (FP):
- Side-effect free functions - That they do not do hidden things beside doing work on the input and returning output
- Referential transparency of functions - A bit of the same as above, that what you put in to a function plus the function itself, completely defines its output
An area where I'm not so happy with some things I've seen in FP, is composability.
In my view, a well designed system or langauge should make functions (or other smallest unit of computation) more easily composable, not less.
What strikes me as one of the biggest elephants in the room regarding FP, is that typical functions compose fantastically as long as you are working with a single input argument, and a single output for each function application, but as soon as you start taking multiple input arguments and returned outputs though, you tend to end up with very messy trees of function application. Even handy techniques such as currying tend to get overly complex if you want to handle all the possible downstream dataflow paths in a structured way.
I (think I) know that monads are supposed to be a highly general way of addressing this problem, but it seems 99% of programmers (including me) have a really really hard time properly understanding the concept well enough that it would help make their code clearer, to them and others.
This is where I find the principles around network composability of Flow-based programming (FBP) shines so brightly.
It solves the composability problem in three basic ways:
- It gives each input and output its own identity, in the form of ports.
- It allows to define the data dependencies between these ports, instead of between functions.
- It allows the setup of these dependencies to happen at any place in the program, which makes it easy to e.g. produce a list of all the connections, as e.g. a simple list of (outport, inport) tuples.
The second point above is significant, as it means data dependencies are defined at the level of data, not functions.
Trying to define data dependencies by defining dependencies between functions, is a major impedance mismatch in my books, and what is causing the need for such complicated syntax in a lot of functional programming.
Flow-based programs on the other hand, are so easy that they can be simplified to two main parts:
- A list of processes (Somewhat the counterpart to functions in FP)
- A list of connections between input- and output ports.

Definitions for functional programming
This page provides all possible meanings and translations of the word functional programming
Programming in a style that, in lieu of assignment, uses procedure calls to bind variables to values.
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. 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. In practice, the difference between a mathematical function and the notion of a function used in imperative programming is that imperative functions can have side effects that may change the value of program state. Because of this, they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.
The numerical value of functional programming in Chaldean Numerology is: 2
The numerical value of functional programming in Pythagorean Numerology is: 3
Images & Illustrations of functional programming
Find a translation for the functional programming definition in other languages:
Select another language:
Discuss these functional programming definitions with the community:
Word of the Day
Would you like us to send you a FREE new word definition delivered to your inbox daily?
Use the citation below to add this definition to your bibliography:
"functional programming." Definitions.net. STANDS4 LLC, 2017. Web. 25 Mar. 2017. <http://www.definitions.net/definition/functional programming>.

[Haskell-cafe] "show" for functional types
haskell at sleepingsquirrel.org
Fri Mar 31 23:10:56 EST 2006
Brian Hulley wrote:
] Here is another example. Consider two functions f and g which, given the
] same inputs, always return the same outputs as each other such as:
] f x = x + 2
] g x = x + 1 + 1
] Now since f and g compute the same results for the same inputs, anywhere in
] a program that you can use f you could just replace f by g and the
] observable behaviour of the program would be completely unaffected. This is
] what referential transparency means.
] However, if you allowed a function such as superShow, superShow f == "x +
] 2" and superShow g == "x + 1 + 1" so superShow f /= superShow g thus you
] could no longer just use f and g interchangeably, since these expressions
] have different results.
Hmm. It must be a little more complicated than that, right? Since
after all you can print out *some* functions. That's what section 5 of
_Fun with Phantom Types_ is about. Here's a slightly different example,
using the AbsNum module from...
> import AbsNum
> f x = x + 2
> g x = x + 1 + 1
> y :: T Double
> y = Var "y"
> main = do print (f y)
> print (g y)
...which results in...
(Var "y")+(Const (2.0))
(Var "y")+(Const (1.0))+(Const (1.0))
...is this competely unrelated?
More information about the Haskell-Cafe

Immutability does more than just change the way you manipulate data in lists. The concept of Referential Transparency will come naturally in F#, and it is a driver in how systems are built and pieces of that system are composed. Execution characteristics of a system become more predictable, because values cannot change when you didn’t anticipate them to change.
Furthermore, when values are immutable, concurrent programming becomes simpler. Because values cannot be changed due to immutability, some of the more difficult concurrency problems you can encounter in C# are not a concern in F#. Although the use of F# does not magically solve all concurrency problems, it can make things easier.
Expressions instead of statements
As mentioned earlier, F# makes use of expressions. This is in contrast with C#, which uses statements for nearly everything. The difference between the two can initially seem subtle, but there is one thing to always keep in mind: an expression produces a value. Statements do not.
In the previous code sample, you can see a few things which are very different from imperative languages like C#:
if...then...elseis an expression, not a statement.
- Each branch of the
ifexpression produces a value, which in this case is the return value of the
- Each invocation of
getMessageis an expression which takes a string and produces a string.
Although this is very different from C#, you’ll most likely find that it feels natural when writing code in F#.
Diving a bit deeper, F# actually uses expressions to model statements. These return the
unit is roughly analogous to
void in C#:
In the previous sample
for expression, everything is of type
unit. Unit expressions are expressions which return no value.
F# arrays, lists, and sequences
The previous code samples have used F# arrays and lists. This section explains them a bit more.
F# comes with a few collection types, and the most commonly used ones are arrays, lists, and sequences.
- F# arrays are .NET arrays. They are mutable, which means that their values can be changed in-place. They are evaluated eagerly.
- F# lists are immutable singly-linked lists. They can be used to form list patterns with F# pattern matching. They are evaluated eagerly.
- F# sequences are immutable
IEnumerable<T>s under the covers. They are evaluated lazily.
F# arrays, lists, and sequences also have array, list, and sequence expression syntax.

Every software program has two things:
- Behavior (what the program does)
- Data (data, is well, data)
When we’re learning about a programming paradigm — like functional programming — it’s often helpful to consider how the paradigm approaches behavior and data respectively.
Behavior, in functional programming, is handled purely using functions in functional programming. Functions are “self contained” pieces of code that accomplish a specific task. They define a relationship between a set of possible inputs and a set of possible outputs — they usually take in data, process it, and return a result. Once a function is written, it can be used over and over and over again.
Data, in functional programming, is immutable — meaning it can’t be changed. Rather than changing data they take in, functions in functional programming take in data as input and produce new values as output. Always.
Functions and immutable data are the only two things you need to ever deal with in functional programming. To make it even simpler, functions are treated no differently than data.
Put another way, functions in functional programming can be passed around as easily as data. You can refer to them from constants and variables, pass them as parameters to other functions, and return them as results from other functions.
This is the most important thing to understand when approaching functional programming.
By treating functions as nothing more special than a piece of data and by only using data that is immutable, we are given a lot more freedom in terms of how we can use functions.
Namely, it allows us to create small, independent functions that can be reused and combined together to build up increasingly complex logic. We can break any complex problem down into smaller sub-problems, solve them using functions, and finally combine them together to solve the bigger problem.
Considering the ever-growing complexity of software applications, this kind of “building-block” approach makes a huge difference in keeping programs simple, modular, and understandable. This is also why developers strive to make their functions as general-purpose as possible, so that they can be combined to solve large, complex problems and reused to speed up development time for subsequent programs.
Ultimately, the reason that functions are so powerful in functional programming is because the functions follow certain core tenets.

Such module systems are present in both OO and non-OO languages.
In summary, I think objects do not compose very well in general – only if the specific objects are designed to compose. Immutability helps to make objects composable by eliminating complex life-cycles and essentially turning the objects into values. Encapsulation also improves composability, and is put to good use in well-designed OO code, but is not unique to OO.
Do functions compose?
Functional programming (FP), on the other hand, is at its very core based on the mathematical notion of function composition. Composing functions f and g means g(f(x)) – f’s output becomes g’s input. And in pure FP, the inputs and outputs are values without life cycles.
It’s so simple to understand compared to the numerous and perhaps even indescribable ad hoc compositions possible in OOP. If you have two functions with matching input and output types, they always compose!
More complicated forms of composition can be achieved through higher-order functions: by passing functions as inputs to functions or outputting functions from functions. Functions are treated as values just like everything else.
In summary, functions almost always compose, because they deal with values that have no life cycles.
What does composition give us?
Having simple core rules for composition gives us a better ability to take existing code apart and put it together in a different way, and thus become reusable. Objects were once hailed as something that finally brings reusability, but it’s actually functions that can achieve this much more easily.
The real key, I think, is that the composability afforded by the functional design approach means that the same approach can be used for both the highest levels of abstraction and the lowest level–behavior is described by functions all the way down (many machine instructions can also be represented as functions).
However, I think most programmers today (including me) don’t really understand how to make this approach work for complete programs. I would love for the functional programming advocates to put more effort into explaining how to build complete programs (that contain GUIs, database interactions and whatnot) in a functional way. I would really like to learn that rather than new abstractions from category theory — even if the latter can help with the former, show us OOP guys the big strategy before the the small tactics of getting there.
Even if we can’t do whole programs as functions, we can certainly do isolated parts of them.

What Is Functional Programming and It’s Most Important Aspects?
Intro to what is functional programming
Functional programming is an interesting programming concept which gains a lot of attention lately. This article presents some of the most important aspects of functional programming in general and provides several examples in Python.
Functional programming is a kind of the declarative programming paradigm where functions represent relations among objects, like in mathematics. Thus, functions are much more than ordinary routines.
In this article, you’ll find explanations on several important principles and concepts related to functional programming:
- pure functions,
- anonymous functions,
- recursive functions,
- first-class functions,
- immutable data types.
A pure function is a function that:
- is idempotent — returns the same result if provided the same arguments,
- has no side effects.
If a function uses an object from a higher scope or random numbers, communicates with files and so on, it might be impure because its result doesn’t depend only on its arguments.
A function that modifies objects outside of its scope, write to files, prints to the console and so on, have side effects and might be impure as well.
Pure functions usually don’t use objects from outer scopes and thus avoid shared states. This might simplify a program and help escape some errors.
Anonymous (lambda) functions can be very convenient for functional programming constructs. They don’t have names and usually are created ad-hoc, with a single purpose.
In Python, you create an anonymous function with the lambda keyword:
lambda x, y: x + y
The above statement creates the function that accepts two arguments and returns their sum. In the next example, the functions f and g do the same thing:
>>> f = lambda x, y: x + y >>> def g(x, y): return x + y
A recursive function is a function that calls itself during the execution. For example, we can use recursion to find the factorial in the functional style:
>>> def factorial_r(n): if n == 0: return 1 return n * factorial_r(n - 1)
Alternatively, we can solve the same problem with the while or for loop:
>>> def factorial_l(n): if n == 0: return 1 product = 1 for i in range(1, n+1): product *= i return product
First Class Functions
In functional programming, functions are the first-class objects, also called higher-order functions — the data types treated the same way as other types.

Functional programming is a type of programming in which the output is determined by the inputs. It is an effective way of breaking complex problems into smaller parts and solving each piece at a time. In the world of software engineering, Java, one of the most popular programming languages worldwide, has adopted this form of programming as an effective and comprehensive way to understand the language and its capabilities.
What is Functional Programming?
Functional programming is a style of programming that focuses on breaking down a larger problem into smaller parts. It is based on mathematics, specifically the concept of lambda calculus, which is the theoretical basis of functional programming. The main idea behind functional programming is that code can be written succinctly and concisely, allowing programmers to focus more on logic and less on control flow. This makes it easier to write code with fewer bugs and fewer lines of code. Additionally, because of the way data is manipulated, functional programming can be more efficient for certain types of problems.
Functional programming also encourages the use of immutable data structures, which are data structures that cannot be changed once they are created. This helps to ensure that data is not accidentally modified, which can lead to unexpected results. Additionally, immutable data structures can be used to create more efficient algorithms, as they can be reused without having to be recreated each time.
Advantages and Disadvantages of Java Functional Programming
Like any programming language, there are a few key advantages and disadvantages of functional programming in Java. One of the main advantages is that functional programming can help programmers write more concise code, while at the same time improving readability. Additionally, it helps reduce coding bugs, as well as avoids dealing with complex control flow. On the downside, it can take some getting used to because of its small syntax and complex functions. Additionally, some may find it difficult to debug, since errors may not be easy to detect.
Another disadvantage of functional programming in Java is that it can be difficult to maintain. This is because the code is often written in a way that is difficult to modify or update. Additionally, it can be difficult to integrate with existing code, as it may require a complete rewrite. Finally, functional programming can be difficult to learn, as it requires a deep understanding of the language and its concepts.
Understanding the Basics of Java Functional Programming
Functional programming in Java doesn’t require a lot of extra knowledge to start getting into it; however, understanding some of the concepts behind it will be helpful in grasping the language.

The concept of state refers to a function/computation global or non-local state of memory at any given time. When the output of a function/computation depends solely on its inputs, we say it is stateless — an example of this is combinatory logic. Conversely, when the output depends not only on the received input but also on history of previous executions, we say it is stateful — this is the case in sequential logic. Notice variables local to some scope are not considered state as they die together with their scope and thus cannot keep history of previous executions. So we only consider global and non-local variables to be state.
Imperative languages describe computations as series of modifications to state. Pure functional languages like Haskell, on the other hand, describe them as function evaluations and have no concept of state. While being stateless comes with several advantages (I won’t talk about it), certain programs require to keep track of previous executions. The problem then becomes: how to implement state in a language that cannot, by definition, have state? We simulate it. From the point of view of the function caller — living in an outer scope than the function callee — functions being called can do only two things: take input, and return a value. Thereby the state has to come from input parameters, and can only survive a function return if returned by the callee once it has been altered. Then the caller is responsible for sequentially feeding the state to a function, collecting the new state from the callee upon evaluation, and feeding it to the next function in the execution chain. Let me illustrate it through an example.
Consider the following example, where we implement a tiny interpreter for a tiny language that supports only variable lookups and variable updates. To represent memory we use a list of pairs of strings, where the first element in the pair is the variable name, and the second one is the value for that variable name:
type Memory = [(String, String)]
We start by writing a function for looking up elements in memory — Given a variable name, and memory, we get its correspondent value (the second element in the pair whose first element matched the variable name).

It is easy to take shortcuts, to be lazy. It is not easy to refactor your code to the point where it is clear what each line in the program does. It is not easy to create a code basis that you can look at five years later and still think ‘Oh, this does that. That makes sense’.
In my opinion, the functional programming approach offers a great way to achieve simplicity. A small function with a single job is simple. The data which serves as input for the function is also simple. The result which is produced from executing the function is also simple. When these three elements come together in the program execution, I can therefore still comprehend each individual part. With functional composition and higher order functions these simple components can become much more powerful without losing their simplicity. By breaking a program down into composable functions with a clear purpose, complexity can be minimized.
Object-orientation deals with complexity by encapsulating it and providing a meaningful abstraction of the problem for the user. This a powerful tool as long as it is possible to ensure that all of the data really has been encapsulated in the desired scope and is not able to be modified from an outer source. However, since immutability is not the default, it is difficult to ensure that objects are only modified within the correct scope. For instance, as soon as a list is exposed in Java, this list can be modified by a subclass or an external library which would produce unexpected behavior at a later point in the program execution. This adds an element of complexity to the language which would not be there in a language where all data is immutable.
This does not mean that a program written in an object-oriented programming language is inherently complex.
I personally am a functional programming enthusiast who spends an enormous amount of her time writing Java programs (a typical object-oriented language). However, I still attempt to make my code as simple as possible by using the Java 8 Stream API, by eliminating mutable state as much as absolutely possible (hello
final keyword!), and most of all by refactoring and rewriting and reviewing my code over and over and over again until I am satisfied with the result (and then I will probably go over it again).
It is also not true that just because a program is written in a functional programming language it is automatically simple.

Posted by Pete McBreen 19 May 2019 at 04:00
Recently I have been looking at Erlang and Elixir, and in the process was reading Coders at Work and came across this quote from Joe Armstrong (pg 213)
I think the lack of reusability comes in object-oriented languages, not in functional languages. Because the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.
If you have referentially transparent code, if you have pure functions –all the data comes in its input arguments and everything goes out and laves no data behind – it’s incredibly reusable. You can just reuse it here, there and everywhere…
Something to think about.

Bryan: Oh, most code in Haskell. Most code in other languages, you can't make any such assumptions about. In Haskell because all of your data is by default immutable, there is no real such thing as a global variable where in between one call to a function and the next call to a function, a global variable that is used by the function could change its value thus changing the output of the function. That just doesn't arise. You've got a much stronger guarantee that a function is going to behave itself.
This plays into comprehensibility, into readability, and it also plays into testing. If you don't need to set up some sort of elaborate mock framework or preload a database with data because most of your code is pure, then you can test your code in a very different way than you would even in a more traditional language. Traditional languages, most testing is built around the idea of say unit testing or load testing. In Haskell you certainly can do those kinds of things, but we also tend to emphasis a more generative way of testing, randomized testing. Because functions are only going to produce data based on their inputs, it's much more straightforward to say with some confidence, "Yes, I believe that I've actually tested this under pretty stringent conditions."
You can express boundary conditions and not worry about anything else.
Bryan: Yeah. Those factors all play into why Haskell or a language with this kind of properties would be of direct interest to somebody who cares about the day-to-day practice of programming. When you come at it from a perspective of "I am going to construct most of my programs and most of my code in a way that is easy to understand, easy to test, easy to refactor and the language's implementation helps me in these ways", then a whole lot of mundane tasks become automatable or things that you can have your tools help you out with.
I can imagine a lot of programmers saying I understand those concepts, but Haskell is difficult to learn or it's difficult to find Haskell programmers or it doesn't have libraries available. To what degree do you believe this element of purity is achievable in a language such as C# or Java or Python or Perl or Ruby?
Bryan: It's doable to an extent. There's a guy named Walter Bright who's been working for several years on a language called D. He's put together D as a better successor language to C than C++.

Add Some Functional Spice to Make Your Code Tastier
Many people use LINQ for years without even realizing they’re using functional programming concepts. I take this as proof that functional programming isn’t beyond the capabilities of the enterprise developer who lacks a strong background in math.
Some of the concepts presented here are neither new nor restricted to functional programming. The benefits of distinguishing between functions that produce side effects from those that don’t is the basis of principles like command-query separation (CQS), for instance.
The goal of this post was not to teach you functional programming. This is honestly beyond my capabilities, as I’m still studying it myself. And besides, there are awesome resources for that purpose if you want to learn more.
Instead, what I wanted here is to give you a little taste of what a functional style can do for your code, which is to make it more expressive, concise, and declarative. Now it’s up to you to try to apply the functional mindset to the code you write.read more...

Why Functional: One Reason
Why functional is better? So many reasons, one comes here: Programming languages are not made for computers, they are for humans to formulate generic solutions computers can solve faster in the details. The imperative style formulates the steps the computer has to follow, the functional style formulates the generic solution as such. Imperative style wants you to act like a machine, functional style allows you to think like a human.

For example, in
let sqr: int code -> int code = fun e -> .<.~e * .~e>.the meaning of
sqr e-- that is, the code it generates -- is the multiplication of two copies of the expression generated by
e. We are sure of that even if we know nothing of
eexcept that it is pure. Likewise, in
let make_incr_fun : (int code -> int code) -> (int -> int) code = fun body -> .<fun x -> x + .~(body .<x>.)>. let test1 = make_incr_fun (fun x -> sqr .<2+3>.) (* .<fun x_24 -> x_24 + ((2 + 3) * (2 + 3))>. *)
make_incr_fun bodyshould produce the code for an OCaml function. The result, shown in the comments, confirms our expectations.
Compositionality lets us think about programs in a modular way,
helping make sure the program result is the one we had in mind. We
ought to strive for compositional programs and libraries. The trick
however is selecting the `best' meaning for an expression. Earlier we
took as the meaning of a code generator the exact form of the
expression it produces. Under this meaning, compositionality requires
the absence of side-effects. Our
test1 is pure and so its result is
easy to predict: it has to be the code of a function whose body
contains two copies of the expression
2+3. Although the confidence
in the result is commendable, the result itself is not. Duplicate
expressions make the code large and inefficient: imagine something
2+3's place. Furthermore,
test1 does not
x and can be lifted out of the function's body -- so that
it can be computed once rather than on each application of the
function. In short, we would like the result of
test1 to look
let test_desired = .<let t = 2+3 in fun x_24 -> x_24 + (t * t)>.
One may remark that a sufficiently smart compiler should be able to
transform the code produced by
performing common subexpression elimination and invariant code
motion.

I've often heard that functional programming solves a lot of problems that are difficult in procedural/imperative programming. But I've also heard that it isn't great at some other problems that procedural programming is just naturally great at.
Before I crack open my book on Haskell and dive into functional programming, I'd like at least a basic idea of what I can really use it for (outside the examples in the book). So, what are those things that functional programming excels at? What are the problems that it is not well suited for?
I've got some good answers about this so far. I can't wait to start learning Haskell now--I just have to wait until I master C :)
Reasons why functional programming is great:
- Very concise and succinct -- it can express complex ideas in short, unobfuscated statements.
- Is easier to verify than imperative languages -- good where safety in a system is critical.
- Purity of functions and immutability of data makes concurrent programming more plausible.
- Well suited for scripting and writing compilers (I would appreciate to know why though).
- Math related problems are solved simply and beautifully.
Areas where functional programming struggles:
- Debatable: web applications (though I guess this would depend on the application).
- Desktop applications (although it depends on the language probably, F# would be good at this wouldn't it?).
- Anything where performance is critical, such as game engines.
- Anything involving lots of program state.

- Expressions are units of code which evaluate to a value.
- Types are classifications of data in a program.
It’s worth noting that everything in the C# column is also possible in F# (and quite easy to accomplish). There are also things in the F# column which are possible in C#, though they’re more difficult to accomplish. It’s also worth noting that items in the left column are not "bad" for F#, either. Objects with methods are perfectly valid to use in F#, and can often be the best approach for F# depending on your scenario.
Immutable values instead of variables
One of the most transformative concepts in functional programming is immutability. It’s often underrated in the functional programming community. But if you’ve never used a language where immutability is the default behavior, it’s often the first and biggest hump to get over. Nearly all functional programming languages have immutability at their core.
In the previous statement, the value of
1 is bound to the name
x now always refers to the value
1 for its lifetime, and cannot be modified. For example, the following code does not reassign the value of
Instead, the second line is an equality comparison to see if
x is equal to
x + 1. Although there is a way to mutate
x by making it
mutable and using the
<- operator (see Mutable Variables for more), you’ll quickly find that it’s easier to think about how to solve problems without reassigning values. This allows you to play to the strengths of F#, rather than treat it as another imperative programming language.
We said that immutability was transformative, and that means that there are some very concrete differences in approaches to solving a problem. For example,
for loops and other basic imperative programming operations are not typically used in F#.
As a more concrete example, say you wish to compute the squares of an input list of numbers. Here is an approach to that in F#:
Notice that there isn’t a
for loop to be seen. At a conceptual level, this is very different from imperative code. We’re not squaring each item in the list. We are mapping the
square function over the input list to product a list of squared values. This distinction is subtle in concept, but in practice it can lead to dramatically different code. For starters,
getSquares actually produces a whole other list.

The job of the first
expression is to carry out that side effect, that is, to add 1 to the lap
count for the specified car. The second expression looks at the value we
just put in a box to determine the return value.
We remarked earlier that
lap isn't a function because invoking it
twice with the same argument doesn't return the same value both
It's not a coincidence that
lap also violates functional programming
by maintaining state information. Any procedure whose return value is not a
function of its arguments (that is, whose return value is not always the
same for any particular arguments) must depend on knowledge of what has
happened in the past. After all, computers don't pull results out of the
air; if the result of a computation doesn't depend entirely on the arguments
we give, then it must depend on some other information available to the
Suppose somebody asks you, "Car 54 has just completed a lap; how many has it completed in all?" You can't answer that question with only the information in the question itself; you have to remember earlier events in the race. By contrast, if someone asks you, "What's the plural of `book'?" what has happened in the past doesn't matter at all.
The connection between non-functional procedures and state also applies to
non-functional Scheme primitives. The
read procedure, for example,
returns different results when you invoke it repeatedly with the same
argument because it remembers how far it's gotten in the file. That's why
the argument is a port instead of a file name: A port is an abstract data
type that includes, among other things, this piece of state. (If you're
reading from the keyboard, the state is in the person doing the typing.)
A more surprising example is the
random procedure that you met in
Random isn't a function because it doesn't always
return the same value when called with the same argument. How does
random compute its result? Some versions of
random compute a number
that's based on the current time (in tiny units like milliseconds so you
don't get the same answer from two calls in quick succession). How does
your computer know the time? Every so often some procedure (or some
hardware device) adds 1 to a remembered value, the number of milliseconds
since midnight.

Suppose we declare that
y = x + 1[This is not an assignment. Imagine a val in front if that is fits your language preferences]. This declares a relationship between x and y, but it does it in a functional style. It would look more functional still if we wrote "y = add 1 x", but that is just sugar.
But what if we have y and we want x? Since we are just declaring a relationship it isn't obvious why we have to change this. But in functional style this has to be changed to:
x = y - 1Functional programs can only run forward, they can't run backwards. Haskell has, of course, a big exception to that: Constructors can be run forward (to construct) or backward (to deconstruct). But perhaps everything that can run backwards should be allowed to (and hence be useable in case statements). In addition to convenience there is a dodgy philosophical point.
When we look at the way the world works it is rather like a giant computer program. And it is particularly like a program in that, on a large scale it pushes forward in an irreversible way. Entropy increases and broken plates never reassemble themselves. And yet at the core is quantum mechanics which is completely reversible.
Haskell and Mercury are two languages in which the interaction with the external world (including mutable data in memory) is explicit. This is a consequence of the fact that both languages are declarative. In non-declarative languages the textual order of the program specifies an order of execution (optimisers alter that, but they are constrained to preserve the semantics, and are forced to make conservative decisions as a result). In declarative languages the compiler generates execution when required, and the thing that brings about that requirement is interaction with the outside world. Since that interaction is explicit, one would hope that the optimiser is never constrained by worrying about what separately compiled code might do.
So it seems that programming should have three levels.
- A core language that is reversible. This specifies what can be handled by cases, though if you allow multiple returns (as Mercury does) then you can expand that.
- Reducing operations (like summing a list) which are intrinsically irreversible.
- Interaction with the unforgiving world which forces an order of execution.
But maybe its not quite that simple.

Developers have to identify concurrent paths and co-ordinate their interactions; something which can be quite difficult to code and fiendishly difficult to debug.
One advantage of FP is that functional code is inherently much easier to parallelise. Since functions don’t access or affect global state and act only on their parameters, you can infer possible parallel paths and have them run concurrently.
A = foo()
B = bar()
Here, the interpreter can run both foo() and bar()in parallel since they are not related and thus are guaranteed not to affect each other.
But wait, there’s more! Both Erlang and Haskell make threading even easier with innovative threading models. Rather than have process communicate through shared memory where you have to handle locking/concurrency yourself, both help make the process of writing multi-threaded code much easier.
- Erlang (Actor/Message Model) : It’s Unix IPC all over again! You basically have pipes which you use to communicate between processes. Messages are asynchronous and not location specific, so processes can migrate to different machines transparently. Errors are piped to related processes as well, giving you robust error handling. No shared memory and scaling it trivial. In fact, the possibility of basically almost unlimited scaling across multiple machines is what really draws me to Erlang and has me drooling like an idiot. Write your code properly and you can just keep slotting in boxes. Erlang also has the ability to update code while it’s running, which means theoretically zero downtime if you’re careful. And it’s all actually in use in the telecommunications industry, so all this is real, not vapour.
- Haskell (Software Transactional Memory Model) : Database transactions, but in local memory! Separate threads run within their own transactions and see a consistent view of the world. No need to explicitly lock bits of shared memory, we just let the system handle all the error prone bits and concentrate on our logic, confidently that our threads won’t be stepping on each other toes. This is a really powerful abstraction and it’s something that had me smacking my forehead, wondering why I didn’t think of it before. However, I see some fundamental problems with multi-machine scalability. This is a fairly well explored problem in the database world and I’m not sure I want my code doing two phase commits and roll-backs in a cluster. Still cool though.
There’s still a long way for me to go yet.

Outline of Class 20: Introduction to Functional Programming
Held: Monday, March 9, 1998
- The language concepts we've looked at so far primarly relate to
imperative languages, which emphasize basic operations and control.
- As we know, there are a number of other important paradigms for programming.
One of the most important is the functional paradigm,
in which programs are collections of function definitions and function
- As always, we should try to define our basis of study.
- What is a function?
- A rule that associates members of one set (the domain)
with members of another set (the range).
- The domain and range may be the same.
- Each member of the domain is associated with at most one
member of the range.
- A (potentially infinite) set of domain/range pairs.
- How can/should/do we define functions?
- By listing all the pairs.
- By providing some sort of general form for pairs
(e.g., regular expressions?)
- In terms of already-defined functions.
- By writing "computer programs" that generate results.
- How do functions on the computer differ from "mathematical"
- In math, we assume that when we apply the same function to the same
value, we get the same result. We don't always make this assumption
in computer languages. For example,
be expected to return a different byte each time.
- In math, we often assume that domains and ranges are infinite.
- When people use the term "functional language", they often mean more
than just the ability to define and apply functions. Definitions of
"functional" often include
- Functions as basic values. That is, you can write functions that
take other functions as arguments or return functions.
- "Atomic symbols" as basic values (so that you can work with symbols
in addition to strings, integers, and such).
- Dynamic lists as built-in data structures.
- Different treatment of memory and variables?
- What are some of the key functional languages? Here are some we'll
study or that the book describes:
- Scheme is a dialect of LISP.
LISP (including its dialects and variants) is perhaps the most widely used
functional language for a number of reasons.
- It's the oldest functional language.

- Basically all the good stuff having immutable data structures and pure functions should give you.
Hopefully this also helps shed some light on why immutability and purity of functions are deemed good things, as well as why Clojure is also such a great language to develop with.

Call by Sharing
In many ways, call-by-sharing is the most intuitive evaluation strategy. It captures the semantics where the caller of the function shares objects with the function being called. The called function can mutate those objects so long as the objects themselves are mutable. Because the objects are shared, any changes will be reflected in the calling function. This convention is applied to all objects being passed.
For immutable objects, call-by-sharing is indistiguishable from call-by-value. Indeed, the key to functional programming is that aliasing (the result of sharing objects instead of copying them) is always 100% safe. This is achievable by forbidding mutation. A class of powerful functional data structures exist that exploit this efficiency. These data structures can usually be efficiently updated without destroying the original copy, because the update aliases large parts of the original data structure instead of mutating it.
whereas the following does not mutate the number:
In the first example, the syntax
A = 0 is a mutation of the array. The
array does not become a different object; it is the same object as before, but
its first element is changed. In the second example, the syntax
n = 0 is very
different. It does not mean “change the value of this number to
it means “rebind the name
n to the new value
0”. This subtlety is the source
of much confusion. In languages with call-by-sharing semantics, names are often
distinguished from objects. Names are bound to objects, and a name can be
rebound to a different object using an assignment keyword. Assignments do not
affect the object the name was originally bound to.
Indeed, if we had written our first example as
then we would have seen a similar result as our second example. Here we are no
longer mutating the array; we are now binding the name
A to a new array.
There is a wealth of resources online that claim that Java is call-by-value, or that Ruby is call-by-reference. These languages are both call-by-sharing. So are these resources wrong? In fact, the former is not wrong. The latter is a little bit of a stretch, but there is some meaning in the nonsense. Rather, this exposes some nuance about what exactly is a value, and what exactly is a reference.

Nevertheless, once you move to a mostly immutable world, you’ll wonder how you ever survived with so much state floating around, running into other bits of state – just like you probably wonder why you ever put up with pointer arithmetic and memory deallocation.
Clojure is built for the real world. Clojure likes – but doesn’t enforce – functional purity. For the cases where it’s necessary to model data using state (see: databases), Clojure gives you safe ways to handle it. And get this: You don’t need a PhD in Monads. (Huzzah!) Now, don't get me wrong – I love Haskell. But as an engineer, I sometimes feel like Clojure is the forgiving parent, and I’m the semi-responsible teenager. It will try to help me live a good life when it can … but when I sneak into the beer cabinet, it looks the other way. (After drinking it, by the way, I immediately feel ashamed. Because really … Smirnoff Ice?)
Clojure redefines the fundamental units of code. Instead of thinking in terms of loop boilerplate, guard clauses, “what if this isn’t initialized yet?”, off-by-one errors, design patterns, serialization, or semicolons, you get to think about data transformations. About defaults that are ultimately flexible. Rubyists know that their language effectively got rid of low-level
forloops. In the same way, Clojure gets rid of imperative iteration in favor of declaration. Your thoughts shift away from place-oriented ideas like memory addresses and gravitate to data structures and functions like
filter. Your “class hierarchy” turns out to be a type system that happens to also lock away well-meaning functions into dark dungeons (more on that in another article), and getting away from that is freeing. Transitioning to an open, abstract world means the intention of your code isn’t obscured by artifacts of computing, by the fact that your code is using and reusing finite memory. Your code is modeled as data, too, by the way. That means you can manipulate it using the same functions you use to manipulate strings and lists and maps. This shift dramatically simplifies and levels-up the tools available for solving new problems.
Clojure code tends to be insanely beautiful. More importantly, though, beautiful code happens to be both readable and efficient (after you learn to love or ignore the parentheses).

(If you’re skeptical, you should read up on persistent data structures.) Speaking of beauty, in Clojure, the physical shape of your code is a nice indicator of how clean it is. For example, when you use side effects in code (like writing to disk, logging, throwing exceptions), it’s becomes pretty obvious from indentation and
!s in method names. And an excess of parentheses at the end of a function call tells you that you may want to break it up into smaller functions. So when you’re looking to clean up code, a quick visual scan can often tell you where to find candidates for refactoring.
Clojure is primed for parallelism. Functional code is easy to reason about, regardless of how many threads you’re working with. For non-functional concerns like database manipulation, Clojure has brought several innovative concepts from academia into the mainstream. (In fact, several of these have seen adoption in other languages, too.) For example, you have Clojure’s software transactional memory (STM) at your disposal – it will help you coordinate state change in a wide range of scenarios. So when you do have your Twitter moment and need to scale, you have loads of options to do so, from lightweight to industrial. You won’t have to change stacks or even the way you think about code. Maybe you’ll convert a
(map ...)call to
(pmap ...)to make it parallel. Or maybe you’ll decide to use agents or refs coordinated by STM. What you won’t be doing is spending weeks scratching your head over semaphores and mutexes.
You can forget context. Why? Because there is no context to learn. Most of your code takes input and produces output, and the pieces of code that don’t follow that pattern tend to stick out. On top of that, each file states its own dependencies, so you’re never left guessing where that strange symbol came from. ("Did one of my libraries monkey-patch my code? Is that a local var or a method name? Did I inherit that, or is it in a mixin?") Given this explicitness, you can move between abstraction layers when its appropriate, but you’re rarely forced to. Each layer also stands on its own. This means it’s relatively easy to ramp up new engineers on one part of your codebase at a time.

A cool feature of a functional language like F# is the ability to partially apply a function. Take this add function:
let add x y = x + y
By partially applying this function we can create new functions like this:
let plus1 = add 1 let plus5 = add 5
The functions we have created plus1 and plus5 both have the signature int -> int. We have partially applied add to a single parameter leaving us with a function that takes one more int and returns us an int. This is a really neat idea.
Building on this if we want to do the same thing with subtract we find that it does not quite work:
let subtract x y = x - y let minus1 = subtract 1 printfn "%i" (minus1 7)
The code above prints -6 when we wanted our minus1 function to subtract 1 from the argument given. This is because unlike with add it matters the order that you give the arguments to subtract. We have another cool trick up our sleeves to solve this:
let subtract x y = x - y let swap f x y = f y x let minus = swap subtract let minus1 = minus 1 printfn "%i" (minus1 7)
The minus1 function above now does what we would expect. To make this work we defined a swap function that swaps the order of the arguments. We can then pass our subtract function to our swap function to produce a new subtract function that takes its arguments in the opposite order. We can now partially apply the new function minus with 1 to give us a new function minus1 that works how we would expect. Having functions as a first class citizen really does lead to some neat code.

Previously we began exploring some theory behind functions. In this post we will look at practical techniques for working with functions.
Working with functions
Using functions is unsurprisingly the bread and butter of functional programming, let us see if we can define a slightly more complex function without butting into too many new concepts. We are going to define a function that cleans up an input
string and then saves it to disk.
// some helper string functions // string -> string let trim (s:string) = s.Trim() // string -> string -> unit let write path content = let sanitized = trim content File.WriteAllText(path, sanitized) // use the write function write "/path/to/file.txt" "Some text to write to file"
This is our first multi-line function and let us go through a few things that may not have been immediately obvious from the single line function. Firstly, note that the body of the function is defined by the indent. For the function the size of the indent does not matter, as long as it is the same throughout the scope. We will dive into this a bit more when we touch on scope in a later post on control flow. Secondly, the value of the last expression is what is returned from the function, in this case
unit. You didn't need to explicitly use
return like in many other languages. This is because functions ALWAYS return something so the compiler can assume that the last expression result is the return.
A big part of the flexibility of functional programming comes from being able to easily tie functions together in interesting ways to build up more complex functionality. Let us apply this idea to the
write function. We are going to pass a function into the
write function that will do the sanitization, thus allowing the client of the function to decide what "sanitized" means.
// ('a -> string) -> string -> string -> unit let write sanitizer path content = let sanitized = sanitizer content File.WriteAllText(path, sanitized) // use the write function write trim "/path/to/file.txt" "Some text to write to file" write (fun (s:string) -> s.Substring(0, 140)) "/path/to/file.txt" "Some text to write to file"
See how we just passed the
trim function in as an argument? This of course could be any function as we see in the second usage.

For example, instead of writing
I can merely write
The latter is instantly more readable, and less typing to boot.
So if it's just a convenient short cut, why all the fuss?
Well, it turns out that because function types are curried, you can write code which is polymorphic in the number of arguments a function has.
For example, the

Have you ever used a pair of scissors instead of a hair clipper to shave? Ever estimated, the length of “my arm is about 50 cm long, so that’s about two arm-lengths?”
There is elegance in using the right tool for a job. And, just like a hair clipper or a measuring tape, programming languages are tools, and using the right programming paradigm for solving a specified set of problems determines a solution’s effectiveness.
Ralf Herbrich from Microsoft Research had over 1,000 lines of C# code for an application that attempted to analyze millions of feedbacks from users, and on a standard desktop, it took forever…well almost…to process the millions of input data. He rewrote the application in F# within 2 days and the results were astonishing! Less than 10 minutes and the millions of input data items were already processed, and it took only 100 lines of code including comments!
Ralf could also process over 10,000 log lines per second, in an application that parsed over 11,000 text files stored in over 300 directories, importing the data into an SQL database, all in 90 lines of F# code written within just hours!
…and this was way back before the F# language platform had matured fully!
Fig 1.1: Evolution of Programming Paradigms
So what is it about F# and functional programming that makes it a vital programming paradigm for business applications?
Explore with me in this and consecutive weekly blog series, on why F#, or at least its functional way is set to take over normal development from C# and will be a must-have a skill for every quality, time and performance conscious.Net developer and/or respective teams.
Functional Programming already lies at the heart of dominant programming frameworks including:
• React [avoiding shared mutable DOM is the motivation for its architecture],
• AngularJS [RxJS is a library of utility operators that act on streams by way of higher-order functions],
• Redux and ngrx/store and more.
Functional programming today is a close-kept secret amongst researchers, hackers, and elite programmers. Most recently, functional programming is part of the rise of declarative programming models, especially in the data query, concurrent, reactive, and parallel programming domains.

If you are a low-level programmer, it may help to think that functional programs have just the same amount of state, but they keep it all in stack frames rather than in a shared heap.
There’s a whole vocabulary relating to this philosophy: “idempotency,” “pure functions,” “side-effect-free,” etc., but the principle is very simple: Functions are easier to understand if they have fewer “moving parts.” Although the philosophy can be universally embraced (one can program functional assembly language), language features can help. In Scala, one can declare a symbol as being a “var”—a traditional variable that can be reassigned—but one is encouraged to use a “val,” which cannot be reassigned (similar to the “final” modifier familiar to Java programmers).
An effect of this philosophy is that functions should have all of their context explicit in the argument list: If you want a “toggle()” function on a Lightbulb, you don’t refer to a mutable field, you pass the old state in and return the new state. In Java, the functional signature might look like Boolean isOn(boolean wasOn). (Or you’d use the Flyweight pattern to return a shared but immutable on-or-off Lightbulb.)
Changing the argument list can be more cumbersome than using hidden state, but as I’ve argued in the past, the rise of unit testing has trained a generation of developers in the practice and shown them the advantages. On the other hand, a corollary of this is that the unit-testing suite of a functional module tends to “lock in” the API more firmly than with traditional object-oriented design. You can avoid such lock-in by having a single argument that is a bag of “context” values, but that strikes me as abandoning the governing philosophy. If explicitness is beneficial, stuffing explicitness away in a bag called “context” is cheating.
Just as every mainstream language has or is gaining first-class functions, most good developers have a sense that avoiding mutable state and explicit context are good things. So again, there’s nothing particularly magical about the syntax or semantics of Scala or any other functional language. They just facilitate these approaches.
And on the grand question of whether a sophisticated static type system such as Scala is a benefit or a hindrance compared to a flexible dynamic type system such as is found in Ruby?

This time, it should add five to each element in an array. Ignoring the rule of three, you jump right ahead into a generalized version, parameterizing the number to be added:
Then yet another request comes in. Now you must write a function that will multiply each element of the given array by, let’s say, three. I won’t add the code sample now because I’m sure you’ve got the picture. By now, you should know better than to hardcode the number, so you’d probably jump ahead to a general version right away. Even then, some duplication would still exist: the loop itself. Hmm…what if you could keep just the loop and instead parameterize the action to be applied on each item?
The Functional Way
Take into consideration what you’ve just read about pure functions—and also your previous knowledge ofprogramming best practices in general—and think of ways the code could be improved.
From my perspective, the main problems are
- The code is too specific. It can’t be easily changed to accommodate other transformations being applied to the array elements. It just performs a sum, and that’s it.
- Too much boilerplate. Look at the previous sample again. Count the lines. There are seven, of which only one really concerns itself with carrying through the business logic of the method.
How would the functional way improve on this? That’s the way I’d write the first example in F#, for instance:
I’m assuming here that “numbers” is a sequence of integers I’ve got somehow. Then I use the map function on the Seq module, passing the sequence as a parameter, along with a function that takes an int and adds three to it.
The Functional Way, .NET/C# Flavor
.NET implements the map operation in the form of the “Select” LINQ extension method. So you could rewrite the F# example above like this:
var result = numbers.Select(x => x + 3);
One important point that needs explaining is that the type of the resulting sequence doesn’t need to match the type of the source sequence. Do you have a list of ‘Employee’ and need a sequence of ints (containing, for instance, their IDs)? Easy peasy:
I think filter is, hands down, the easiest operation of the bunch.

varLookUpList :: String -> Memory -> Maybe String varLookUpList name  = Nothing varLookUpList name ((n,v):xs) = if name == n then Just v else varLookUpList' name xs
Next we need to return the modified data structure to the caller so that the caller can pass it to the new callee, and thus preserve the modifications that have been made during the current call. Perhaps this is not the case when we are just “looking up” values, but in general it is. To do this we need an extra input to receive the state, and an extra output to give back the mutated state together with whatever output the function was returning anyway.
In general we want to turn something like this (for functions that lookup values):
function :: a -> state -> b
or like this (for functions that alter a data structure):
function :: a -> state -> state
into something like this:
function :: a -> state -> (b, state)
Our example then gets modified as follows — Notice we return back the memory unmodified :
varLookUp :: String -> Memory -> (String, Memory) varLookUp name mem = case varLookUpList' name mem of (Just s) -> (s, mem) Nothing -> ("Not found", mem) where varLookUpList' :: String -> Memory -> Maybe String varLookUpList' name  = Nothing varLookUpList' name ((n,v):xs) = if name == n then Just v else varLookUpList' name xs
Updating state is an assignment’s side effect. Other than that, assignments evaluate to the value of the variable on the left hand side of the assignment… at least on our language.

Because the overhead of doing something concurrent, you want to ship it off to be done somewhere else, you want it to be of a certain size: "You must be this big to be worth the overhead of shipping somewhere." We’re driving that overhead down. But today, that’s too fine-grained for most applications of exploiting that.
But the other area that functional languages are great at (the pure ones) is immutable state. You copy, you modify a vector, one element in it, we just got a whole new vector with that one element change, which is great. And immutable, you need no locking, it’s wonderful—except that there are pure functional languages like that, and then there are functional languages that people actually use, for commercial code. Because you just aren’t going to copy every—
Ted: [Laughs.] You just earned a hate mail from somebody on that line.
Herb: I know! But the reality is that everybody has to make exceptions, because, for efficiency, you’re just not going to copy a million-element vector every time you change an element, so there’s always a compromise. Immutability is great, but there needs to be that balance. The one thing you see coming from functional languages that are coming into all languages are Lambdas and closures. C#, anonymous delegates; Java is working on it; and, as you know, C++0x.
Bjarne: I’d just like to add to this: The functional program community has owned a huge chunk of the educational establishment for 30 years. They have explained to generations of programmers why it was wonderful and has never gotten traction in industry. So, from my perspective, there’s lots I like, but I’m not going to bet everything on being able to go functional, because lots of people (probably smarter than me) have done that and failed.
Bjarne: We’re trying to adopt what can’t fit with other things. This is why I sort of talk about multi-paradigm programming, trying to figure out how to combine traditional C styles with object-oriented programming and generic programming; finding a sort of (if you’ll excuse me) "sweet spot" in the space, where you can do a lot of things—where you can do it with greater safety, easier writing, and still good performance. It’s tricky.
Herb: One thing about multi-paradigm development, C++ has always been big on that.

One aspect I enjoy about functional programming is the immutable and static nature of data. Rather than having to think about how an object changes over time, often I get to think about data that is static, unchanging, which is easier to visualize. Sometimes I even think of functions not as a process, but a static relation between input and output. This can often be done with probability distributions, for example.
Traversable functors, which is functional programming’s answer to iterators, by definition appear to require dynamic behaviour to understand them.
Traversable functors come with a
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)The
traversetakes an applicative action
h :: a -> f band uses it to iterate through all the elements of the container
t a, producing a new container
t bwhile sequencing all the applicative effects of the action.
In order for traversals to be proper, they need to satisfy three laws. Laws one and two are analogous to the functor laws
traverse Identity = Identity
traverse (Compose . fmap g . f) = Compose . fmap (traverse g) . traverse f
The zeroth law is more difficult to state, but is easier to prove. It says that for every pair of applicative functors
eta :: F a -> G a is an applicative transformation, which means
eta (pure x) = pure x
eta (f <*> x) = eta f <*> eta x
traverse, which means
eta . traverse f = traverse (eta . f)
The zero law is a free theorem, which effectively means one can always take it for granted for any
traversal function one write.
There is a static way of understanding a traversable functor satisfying these laws. Recently I have been working with Mauro Jaskelioff to prove that every traversable functor is a finitary container. For those eager for a preview, a Coq proof is available.
The upshot of all this technical work is that the
traverse function is secretly a recipe for simply separating out from a container,
t a, a list of the values it contains.
This separation allows one to update or replace the values of the container with new values.
This static understanding has nothing to do with sequencing effects.

In fact, all of the functions in this example will have a similar format like this:
Input: a Stack plus other parameters Output: a new Stack
Next, what should the order of the parameters be? Should the stack parameter come first or last? If you remember the discussion of designing functions for partial application, you will remember that the most changeable thing should come last. Youíll see shortly that this guideline will be born out.
Finally, the function can be made more concise by using pattern matching in the function parameter itself, rather than using a
let in the body of the function.
Here is the rewritten version:
let push x (StackContents contents) = StackContents (x::contents)
And by the way, look at the nice signature it has:
val push : float -> Stack -> Stack
As we know from a previous post, the signature tells you a lot about the function. In this case, I could probably guess what it did from the signature alone, even without knowing that the name of the function was "push". This is one of the reasons why it is a good idea to have explicit type names. If the stack type had just been a list of floats, it wouldn't have been as self-documenting.
Anyway, now let's test it:
let emptyStack = StackContents  let stackWith1 = push 1.0 emptyStack let stackWith2 = push 2.0 stackWith1
With this simple function in place, we can easily define an operation that pushes a particular number onto the stack.
let ONE stack = push 1.0 stack let TWO stack = push 2.0 stack
But wait a minute! Can you see that the
stack parameter is used on both sides? In fact, we donít need to mention it at all. Instead we can skip the
stack parameter and write the functions using partial application as follows:
let ONE = push 1.0 let TWO = push 2.0 let THREE = push 3.0 let FOUR = push 4.0 let FIVE = push 5.0
Now you can see that if the parameters for
push were in a different order, we wouldnít have been able to do this.

I don't think I quite understand currying, since I'm unable to see any massive benefit it could provide. Perhaps someone could enlighten me with an example demonstrating why it is so useful. Does it truly have benefits and applications, or is it just an over-appreciated concept?
(There is a slight difference between currying and partial application, although they're closely related; since they're often mixed together, I'll deal with both terms.)
The place where I realized the benefits first was when I saw sliced operators:
IMO, this is totally easy to read. Now, if the type of
You mentioned C# lambdas in a comment. In C#, you could have written
If you're used to point-free style, you'll see that the
which is awful due to the lack of automatic partial application with C# lambdas. And that's the crucial point to decide where currying is actually useful: mostly when it happens implicitly. For me,
Now, if readable, the benefits sum up to shorter, more readable and less cluttered code -- unless there is some abuse of point-free style done is with it (I do love
Also, lambda calculus would get impossible without using curried functions, since it has only one-valued (but therefor higher-order) functions.
* Of course it actually in
Update: how currying actually works.
Look at the type of
You have to give it a tuple of values -- not in C# terms, but mathematically spoken; you can't just leave out the second value. In haskell terms, that's
which could be used like
That's way too much characters to type. Suppose you'd want to do this more often in the future. Here's a little helper:
Let's apply this to a concrete value.
Here you can see
Fortunately, most of the time, you don't have to worry about this, as there is automatic partial application.
It's not the best thing since sliced bread, but if you're using lambdas anyway, it's easier to use higher-order functions without using lambda syntax.

For example in F# if you write
then that's it x is one forever and ever. This is immutability of reference or value depending on the type of data involved.
Hold on a moment doesn't banning variables mean that you can't write things like
You can't increment a variable because there are no variables. Once a symbol is bound to a value it doesn't and can't change.
OK, so how do functional programmers do things that "normal" dysfunctional programmers take for granted - like count how many times something happens or add up the first ten integers?
The answer is that in functional programming no symbol is ever bound to a value until its final value is known. This is the "frozen time" approach of math.
Take, for example, the problem of adding up the first ten integers. In most programming languages you would write something like:
That is, you would use a for or some other sort of loop to form a running sum until you had the answer, i.e. 45. The symbol "total" would change its value all through the loop until it got to the final answer. It is a machine that whirs into life to loop round counting things.
If you want to make symbols immutable then you can't do things in this way. You have to use recursion to put off binding any intermediate results until you have the final answer.
The way to do this is to suppose that we have a function that returns the sum of integers from x to 9, e.g. sumto9(x). Well it's obvious that sumto9(9) is 9, it is also obvious that sumto(8) is 8+9 or 8+sumto(9). You can also see that this generalizes to sumto(x)=x+sumto9(x+1) with sumto(9) defined as 9. Writing this as a recursive function gives:
if(x=9) return x;
Now you can write:
total never has to be set to an intermediate value, it just gets bound to its final value in one go.
You could argue that all of the "variables" of the process are now in the recursion, but notice that x doesn't change - it just gets created in a new context each time the function is called. That's the whole point of function parameters - they allow things to change by being re-created - see object immutability discussed earlier.

I embraced functional programming through Scala starting with the great Marting Odersky’s course in Coursera, following with the Reactive Programming course in Coursera (a second edition of which will start shortly and I really recommend you to sign up and follow it), and later on working with Play framework and Akka streams.
I spent a few years programming in Java in a purely imperative way, and as soon as I could understand the functional approach, I realized it is a great way to focus on the essence of the problem, and it provides a more organic way to decompose reasoning and handling complexity.
Of course the language itself doesn’t guarantee that the approach is functional: if you want you can write Scala almost like Java without semicolons. But despite not being purely functional and allowing mutable variables, Scala provides all the features to put in practice purely functional approach. Moreover the syntax is very similar to Java so the transition from Java, from the language point of view, is pretty smooth.
When I have seen the first examples of functional code I appreciated the fact that it provides the language tools to model directly mathematical functions. For example a mathematical function $f$ from $A$ to $B$:
is translated into a definition of a function in Scala as (the
??? mean that the function is still undefined):
Functions in Scala are first class citizens, and they can be passed as arguments to other functions. This allows to compose things in a very straightforward way that procedural programming simply wouldn’t allow.
1 2 3 4
We know the explicit way of finding N given $\Delta x$ and $\pi$, however let’s exploit a great feature of Scala which are
Streams and lazy evaluation (see http://www.scala-lang.org/api/2.11.5/index.html#scala.collection.immutable.Stream).
We can define the
Stream of $x_n$ as a potentially unbounded sequence of doubles, with the guarantee that the next number will be generated on demand, lazily, only when required:
1 2 3 4
Here we did two things: we created a
Stream, where no value is allocated yet, all the values of which are created on demand, and we defined it with a
def and not with a
val in order to save memory allocation once we consumed the stream, as we want just the $x_n$ to be produced to generate the sum and we don’t want to retain it afterwards.

Do you think Computer Science equals building websites and mobile apps?
Are you feeling that you are doing repetitive and not so intelligent work?
Are you feeling a bit sick about reading manuals and copy-pasting code and keep poking around until it works all day long?
Do you want to understand the soul of Computer Science?
If yes, read SICP!!!
In FP world people bash assignment. They say it is the root of all evils. But is it really true?
First we have to ask why assignment? The answer is simply to achieve better modularity in program design. Let’s see an example.
Suppose we are designing a counter, which simply starts from 0, and increase by 1 every time it is called.
Let’s first implement it using assignment.
(define (make-counter) (let ((count 0)) (lambda () (set! count (+ count 1)) count)))
make-counter is a constructor, which returns a lambda that has access to a local variable
Now let’s try to use it inside exponential function.
(define (exp x n counter) (if (> (counter) n) 1 (* x (exp x n counter))))
I know this is a bit contrived. But it is still a valid implementation and kind of straightforward.
Now, let’s implement the
counter without using any assignment.
(define (counter current-count) (+ current-count 1))
A counter is just a function that increase the current count by one, fair enough.
Now let’s use it in the same exponential function.
(define (exp x n counter current-count) (let ((new-count (counter current-count))) (if (> new-count n) 1 (* x (exp x n counter new-count)))))
Notice that the function takes one more parameter
current-count. And it is always 0 when calling the function.
(exp 4 2 0). Imagine if a procedure
A needs to know to put 0 as the
current-count. In other words, the internals of
counter has leaked into
If you think this is not too bad, let’s tweak the contrived example to be even more contrived.
Suppose that the we want to control the speed of the counter. Say we want to increase 3 by each count.
In the assignment version of the counter, we just change to
(set! count (+ count 3)). No other places needs to change.
While in the non-assignment version.

- It includes "nonfunctional" components which support traditional
- FP was defined by John Backus to illustrate some of
the possibilities of programming with functions and no notion of
an underlying architecture. FP provides no assignment or direct access
- ML is a popular functional lanuage originally
developed as part of a program verification system. It is currently
known for its use of modern lanugae concepts (an excellent type system,
exceptions, polymorphism, etc.)
- Haskell is one of the newest "big" functional languages.
Haskell is notable for making no comprimises on functional purity --
there are no side-effecting operations in Haskell. Haskell also uses
an intersting evaluation strategy called lazy evaluation.

fun x y z -> ...is more efficient than the ``tupled'' (or ``uncurried'') form
fun (x,y,z) -> ...The bytecode compiler ensures that a complete application of a curried function (that is, arguments are provided for all parameters -- no partial application) executes without heap allocation. In contrast, applying an uncurried function to a tuple of arguments always heap-allocate the tuple, which is costly both because of increased memory traffic (writes to fill the tuple, loads to access its components) and increased load on the garbage collector.
The native-code compiler optimizes both curried and tupled functions, avoiding heap allocation and using registers to pass the parameters.
let rec f x y z = ... f x y e1 ... ... f x y e2 ...where all recursive calls have the same
yparameters as on entrance, is it worth rewriting it as below?
let f x y z = let rec local_f x = ... local_f e1 ... ... local_f e2 ... in local_f xThe short answer is: it depends, but in doubt don't do it.
It depends on the number of invariant parameters: parameter passing is cheap, so don't bother making a local function if you have only one or two invariant parameters.
It also depends on the expected number of recursive calls of the
function: building the closure for
local_f adds a
constant overhead to the initial call of
f, which can be
overcome by the fact that recursive calls to
more efficient than recursive calls to
f if there are
many recursive calls; but if
f does not recurse very
deeply, the cost of building the closure for
make the ``optimized'' form less efficient than the naive form.
forloop is slightly faster than the corresponding recursive function (and a lot more readable too!). For numerical iterations (ints and floats), loops are probably slightly more efficient. On the other hand, assignment to a reference holding a heap-allocated data structure can be relatively expensive (due to the generational garbage collector), so it is better to stick with recursive functions when working over data structures.
o(memory overhead) parameter. The major collector is incremental: it does a ``slice'' of major collection each time a minor collection occurs. To decide how much work to do at each minor collection, it estimates the allocation rate of the program and bases its ``speed'' on that.

Top-level vs. local recursion
Compare the following two implementations of map. The first one uses top-level recursion
map :: (a -> b) -> [a] -> [b] map _  =  map f (x:xs) = f x : map f xs
whereas the second one uses local recursion
map :: (a -> b) -> [a] -> [b] map f = let go  =  go (x:xs) = f x : go xs in go
Although the first version is shorter, there some reasons to prefer the second version for stylistic reasons:
- It clearly shows that the 'f' is not "altered" in the recursion.
- You cannot accidentally 'jump' into the wrong loop. I often have multiple implementations of the same function which differ in laziness or performance. They only differ slightly in name and it happened too often that after copy&paste the recursive call went to a different (and thus wrong) function.
- The local loop is probably also more efficient in execution, because the compiler does not need to move the around. However, if this is actually more efficient then the compiler should do such a transformation itself.f
which is both short and allows deforestation.
- Haskell-Cafe on HLint 1.2

To be fair, math does have variables, but they are used in very restricted ways compared to the way they are used in programming; and where they are used more like as in programming then the math begins to look like programming. Math mostly deals with change by taking a snapshot and making everything static - what else is a function in the f(t) sense other than frozen time? It isn't a dynamic process but a subset of the Cartesian product of two sets.
So what does all this have to do with functional programming?
The simple answer is that functional programming aims to remove the state and mutability out of programming and make it more like static maths. In other words it attempts to freeze time out of programming in the same way maths does.
This is the usual "standard" statement of functional programming, but it isn't quite as pure as this sounds. There is a lot of messiness in functional programming but it is often wrapped up in so much jargon you can't really see it for the clutter.
In math functions are stateless. If you evaluate sin(Pi) at 12 noon today then you will get the same answer when you evaluate it at 12 noon tomorrow. In math functions don't change.
In functional programming functions aren't just ways of grouping things together in a neat package. Function are first class objects and can be used anywhere a number or an expression can be used. They are also "higher order" functions which can accept functions and spit out functions as their result. Most important of all functions never change the state of the system - they don't have side effects.
The no-side effect rule is a bit difficult to stick to because if the system is going to deliver a result or interact with a user then side effects are essential and some state has to change.
You will often hear the term immutable used in connection with functional programming and exactly what it means is often confused with a simpler idea - object immutability.
Object immutability is an easy idea. For example if a String object is immutable it can't be changed but this doesn't mean you can't do:
What happens in this case is that the String object that the variable string1 is referencing is destroyed and a new object created with "A" attached to its right hand end. This is an almost trivial meaning of immutable and if it wasn't pointed out it would go unnoticed.
The real important use of immutable in functional programming is the way variables don't - vary that is.

This makes the Scala OO model purer than that of some other languages (of course in languages like Ruby where classes are objects class variables and methods have more or less the same meaning and the model is just a pure if not purer).
Traits – the evolution of interfaces
- Traits are interfaces on steroids
- They can contain state as well as behaviour
- Think of them more as Ruby’s mixins than Java’s interfaces
- They can be implemented on the fly by objects
- They are too complex to be properly explained in one short blog post :–)
Functional programming has many aspects, but to get the bulk of it you need just two magical ingredients – support for functions as objects and a nice array of immutable data structures. Scala, naturally, has both. Traditionally OOP languages have rarely had much support for functional programming, which makes it awkward to express some problems in them. Steve Yegge wrote an excellent article on the subject some time ago – “Execution in the kingdom of the nouns”.
Return of the verbs
Functions are first class objects
- val inc = (x: Int) => x + 1
- inc(1) // => 2
- List(1, 2, 3).map((x: Int) => x + 1) // => List(2, 3, 4)
- List(1, 2, 3).map(x => x + 1)
- List(1, 2, 3).map(_ + 1)
Closures are basically functions that have captured variables from an external scope (variables that were not parameters of the functions). Closures are often used as the parameters of higher-order functions (functions that take functions as parameters):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Functional data structures
Functional programming revolves around the concept of immutability – nothing is ever changed – we have some input, we get some output and the input is not changed in the process. Consider a simple operation like an addition of an element to a list:
- the operation could modify the list to which the element is being added
- the operation can return a new list that is the same as the original, but has the additional element
Functional programming favours the second approach and Scala as a functional programming language provides data structures with the desired behaviour.

Java’s Comparator Interface is a good example of a common FP idiom, where you pass along a bit of code as a parameter as well as the data and have the code act on the data. Java 7 might have closures as well, which are already to be found in Ruby. Python has things like list comprehension, which has a distinctly FP feel and so on. I thought I might as well experience all these concepts in one integrated functional package rather than piecemeal.
FP vs OOP
Invariably when you start to talk about a new programming model, you’re met with slack jaws, blank stares and mewling cries of “But, but, but… OOP!”. Now I’m not one to deride OOP because I like the concept quite a lot. It’s a great fit for a range of applications and can really help model a lot of complex domains and interactions. However, it isn’t the end all and be all of computing that the OOP aficionados (and their groupies) make it out to be. One particular domain which seems to be a bit of a mismatch is the Web.
Most web programming involves a lot of pointless conversion from flat data to OOP and back again. Take a basic CRUD application. The user enters plain data without any OOP savvy behaviours or what have you. Just characters strung together. When he hits submit, we convert this data to fit into our OOP model and play around with it in the middle layer. We then flatten it once more and stick it in the database. We might also have some stored procedures in the database as well (usually written in a non-OOP language/manner). So the only place we’re really using OOP is in the middle layer and most of what we’re doing is simply converting data from one model to another. It’s just a huge waste of time. Embrace the fact that all we want to do is apply transformations to data and use FP (which is admirably suited to the role) to do just that.
I mean, what’s so Object Oriented about Servlets? They're actually very functional. You usually just implement one method/function which accepts user data as parameters, munges it and then forwards more data somewhere else, where we display the response.
As far as reuse goes, OOP hasn’t proven to be all that. Look at the Java Library.

The UNIX Philosophy has nine principles. These same principles are core to functional programming as I understand it.
Below find the nine principles of UNIX interpreted in terms of FP, ordered by the strikingness of the parallel.
1. Small is beautiful.
Small functions, small abstractions. The simpler the function, the easier it is to see what it will do.
2. Make each program do one thing well.
Each function should have one purpose.
9. Make every program a filter.
Make it composable! It is composability that builds functions and abstractions into larger systems without complicatedness.
6. Use software leverage to your advantage.
Composability leads to reusable parts. Also, write tiny DSLs for your own use.
3. Build a prototype as soon as possible.
The interactive REPL lets us prototype functions.
4. Choose portability over efficiency.
Don’t depend on the environment, even if it would be easier to root around in the database or system properties. Keep functions “data in, data out.”
8. Avoid captive user interfaces.
Imperative style may be most obvious to the programmer, but it is not the most flexible for her long-term use. Avoid inflexible contexts that look easy-to-use.
5. Store data in flat text files.
Functions should have visibility into the data, and its structure should be clear. With immutable data, choose clarity over encapsulation.
7. Use shell scripts to increase leverage and portability.
OK, yeah, I got nothing.
principles drawn from: http://www.pappp.net/?p=969

But I should be able to use a mundane foreach() or even a dreaded for() loop, have the compiler examine my scope and see that I'm using my variables in an immutable fashion, and generate functional code from my imperative code.
What I am getting at is that in the olden days we used synchronous macros do a series of tasks and even though it was mediocre at best, it gave tremendous leverage to the developer. Today the amount of overhead required to map-reduce things or chain promises and carry the mental baggage of every timeout and failure mode is simply untenable for the human brain beyond a certain complexity. What we really need is to be able to read and write code imperatively but have it executed functionally, with every side effect presented for us.
I realize there is a lot of contradiction in what I just said but as far as I can tell, complexity has only increased in my lifetime while productivity has largely slipped. Shifting more and more of the burden to developer proficiency is just exactly the wrong thing to do. I want more from a typical computer today that is 1000 times faster than the ones I grew up on.
I think you've got this exactly backwards. Functional programming lets you think at a higher level of abstraction (data flow) than imperative programming (control flow). The compiler then applies elbow grease to translate your high-level data flow transformations into low-level control flow constructs.
Let's translate your statement back a generation and see how it sounds: "I think the move towards structured programming, and putting the onus on developers to do the mental elbow grease of converting what are largely assembly-level tasks (branch, copy, add a value to a register) into structured code (if, while, for) has done a great disservice to software engineering, especially with respect to productivity."
Hopefully you can understand how silly that seems to a modern programmer.
If you only ever work on things that map well to functional programming then you'll naturally think it's superior to imperative programming. Likewise, if you only ever work on things that map well to imperative programming, then the functional programming approach seems a bit silly.
It will not always be easier, but it certainly provides more control over the execution flow.
That said, you can write spaghetti code in any language. =)
I’m to the point where I am thinking about rejecting all of this and programming in synchronous shell-scripting style in something like Go, to get most of the advantages of Erlang without the learning curve.

These days, I am deeply in love with Microsoft’s F# language and Apple’s Swift language. F# on one side has picked the good parts from Functional languages like ML and oCaml + Imperative languages / Object-Oriented language like C#.
Swift on the other end is a multi-paradigm languages picking language ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
While learning these languages, one question (in fact multiple questions) always comes to my mind:
- “What is a functional language and what is imperative language? and how are they different ”
Here are few answers which I read/ got from books and on the web.
The functional programming paradigm was explicitly created to support a pure functional approach to problem solving. Functional programming is a form of declarative programming. In contrast, most mainstream languages, including object-oriented programming (OOP) languages such as C#, Visual Basic, C++, and Java –, were designed to primarily support imperative (procedural) programming.
With an imperative approach, a developer writes code that describes in exacting detail the steps that the computer must take to accomplish the goal. This is sometimes referred to as algorithmic programming. In contrast, a functional approach involves composing the problem as a set of functions to be executed. You define carefully the input to each function, and what each function returns. The following table describes some of the general differences between these two approaches.
|Characteristic ||Imperative Approach ||Functional Approach |
|Programmer focus ||How to perform tasks (algorithms) and how to track changes in state ||What information is desired and what transformations are required |
|State changes ||Important ||Non-existent |
|Order of execution ||Important ||Low importance |
|Primary flow control ||Loops, conditionals, and function (method) calls ||Function calls, including recursion |
|Primary manipulation unit ||Instances of structures or classes ||Functions as first-class objects and data collections |
Although most languages were designed to support a specific programming paradigm, many general languages are flexible enough to support multiple paradigms. For example, most languages that contain function pointers can be used to credibly support functional programming. Furthermore, in C# 3.0 and Visual Basic 9.0, explicit language extensions have been added to support functional programming, including lambda expressions and type inference. LINQ technology is a form of declarative, functional programming.

It calls the function on the items of the iterable and returns a new iterable with the items for which the function returned True or anything that is evaluated as True. For example:
>>> list(filter(lambda item: item >= 0, [-2, -1, 0, 1, 2])) [0, 1, 2]
The statement above returns the list of non-negative items of [-2, -1, 0, 1, 2], as defined with the function lambda item: item >= 0. Again, the same result can be achieved using the comprehension:
>>> [item for item in [-2, -1, 0, 1, 2] if item >= 0] [0, 1, 2]
Reducing is performed with the function reduce from the module functools. Again, it takes two arguments: a function and iterable. It calls the function on the first two items of the iterable, then on the result of this operation and the third item and so on. It returns a single value. For example, we can find the sum of all items of a list like this:
>>> import functools >>> >>> functools.reduce(lambda x, y: x + y, [1, 2, 4, 8, 16]) 31
This example is just for illustration. The preferred way of calculating the sum is using the built-in reducing function sum:
>>> sum([1, 2, 4, 8, 16]) 31
Immutable Data Types
An immutable object is an object whose state can’t be modified once it’s created. Contrary, a mutable object allows changes in its state.
Immutable objects are generally desirable in functional programming.
For example, in Python, lists are mutable, while tuples are immutable:
>>> a = [1, 2, 4, 8, 16] >>> a = 32 # OK. You can modify lists. >>> a [32, 2, 4, 8, 16] >>> a = (1, 2, 4, 8, 16) >>> a = 32 # Wrong! You can't modify tuples.

We could argue that since an imperative program is often 90 percent assignment, and a pure functional F# program has no assignment, it could be 90 percent shorter, and more modular.
To see its advantages clearer, we must look at what F# permits rather than what it prohibits. For example, it allows us to treat functions themselves as values and pass them to other functions. This might not seem all that important at first glance, but its implications are extraordinary. Eliminating the distinction between data and function means that many problems can be more naturally solved. In addition to treating functions as values, F# offers other features that borrow from mathematics and are not commonly found in imperative languages.
For example, F# offers curried functions, where arguments can be passed to a function one at a time and, if all arguments are not given, the result is a residual function waiting for the rest of its parameters. It also offers type systems with much better power-to-weight ratios, providing more performance and correctness for less effort.
“The functional programmer sounds rather like a medieval monk, denying himself the pleasures of life in the hope that it will make him virtuous.”
Herewith some virtues we will come across in using F#
Common programming tasks are much simpler in F#, examples being creating and using complex type definitions, list processing, comparison and equality, state machines, and more.
Because functions are treated as first-class objects, it is very easy to create powerful and reusable code by creating functions that have other functions as parameters or combine existing functions to create new functionality.
F# has a more powerful type system that prevents many common errors such as null reference exceptions, values are immutable by default, and that prevents a host of errors. We can encode business logic using the type system itself in such a way that it is actually impossible to write incorrect code or mix up units of measure, relegating unit tests as just a matter of formality, as their need is greatly reduced.
F# is not cluttered with unnecessary coding “noise” such as curly braces, semicolons, and more. You never have to specify an object type, due to a powerful type inference system, and compared with C#, it will always take fewer lines of code to solve the same problem, making maintenance less of a nightmare.
Asynchronous programming is very easy, as is parallelism with its inbuilt libraries. F# also has a built-in actor model, excellent support for event handling and functional reactive programming.

The academic and mathematical origins of functional programming scares an average programmer with words like type inference, closures, currying, continuations, monads, impredicative higher-ranked types, etc, but in these blog series, I will be dispelling demystifying their widely perceived complexity, explaining the concepts in a way mere mortals should understand.
This blog series is about showing you how easy and more effective it is to use the F# as a general purpose tool, and its applicability with an emphasis on the specific problem domains where it can lead to boosts in productivity.
Throughout this blog series, you will discover that whilst F# isn’t the best tool for every situation, it is the perfect tool for many situations. Along the way, you will develop a knack for functional programming, with collections of concepts that will help you rethink and improve your programs regardless of your current programming language.
A Brief Comparison With Other Functional Languages
F# shares a core language with OCaml programming language, and in some ways can be considered an “OCaml for.NET.” It also draws from Haskell’s advanced features called sequence expressions and workflows. Despite similarities to OCaml and Haskell, F# is quite different, in particular, its approach to type inference, object-oriented programming, and dynamic language techniques, is considerably different from all other mainstream functional languages.
F# embraces .NET techniques such as dynamic loading, dynamic typing, and reflection, and it adds techniques such as expression quotation and active patterns.
F# is unique amongst both imperative and declarative languages in that it is the middle road where these two extremes converge. It takes the best features of both paradigms and combines them into an elegant language that both scientists and developers identify with.
F# differs from many functional languages in that it embraces imperative and object-oriented programming. It also provides a missing link between compiled and dynamic languages, combining the idioms and programming styles typical of dynamic languages with the performance and robustness of a compiled language.
Why Functional Programming and F#
F# encourages a different way of thinking about programs. It is based on the powerful principle that behaviour is strictly determined by input so that the same input will always produce the same behaviour. One of F#’s greatest strengths is that you can use multiple paradigms (OO, Imperative, Declarative) and mix them to solve problems in the way you find most convenient, but unlike other paradigms, it allows no side effects.

Let me elaborate.|
When we think about building sw abstractions, it is common to note that the first implementation we build is rarely the most efficient implementation possible. It may be fast enough, but often we need to change the implementation to get better performance. For example, we may need to change the data structures used, or the choice of algorithms.
Still, if the abstraction is good, which means it has a well designed interface, we can change the implementation while keeping the interface stable. This is one of the major benefits of information hiding and data abstraction (another benefit is seperate compilation, by the way).
The simple implementation we designed at first, can be any implementation that supports the specification. Wouldn't it be great if we could arrive at some such implementation, simply by making transformations on the (algebraic) specification?
Of course, it would be even better if we could than optimize the implementation by using program transformations on the basic implementations!
(Of course, this will only get you so far. It will not reinvent new algorithms for you. But heck, you are paid to do some of the work yourself!)

Closing Over Simplicity
In the world of software development, there are two similar goals that run somewhat opposed to each other. One is speed and ease of creating new software. It’s important to go fast and get things done. Another goal is code that’s simple to reason about and easy to maintain and extend. It’s very easy to quickly generate reams of code that basically works, but leaves behind a complex web of entangled logic. If you’d like to learn more about these two somewhat opposed ideas, and the characteristics of each, do yourself a favor and watch Rich Hickey’s talk Simple Made Easy. (There are two recordings of this talk. This is a more recent version given in March of 2012.) Once you watch it, wait a week and watch it again. Many have reported getting more out of it with repeated viewings.
What are the key components of maintainable software? One is code that is simple to reason about. Another is doing more with less. If solution A takes 20 lines and the functionally equivalent solution B takes 10, is solution B better? Possibly, unless it abstracts away the details to the point where if a second developer comes along, they cannot understand it.
Clojure is a relatively new language, created in 2008 by the previously mentioned Rich Hickey and designed with simplicity over ease in mind. It’s based on Lisp which is relatively old, but remains relevant. Clojure runs on the JVM and achieves near native-Java speed while leaving behind a lot of the cruft of the host language. It encourages (but doesn’t enforce) functional programming concepts. Everything distills down to functions that operate on data structures. Ideal functions are pure, free of side effects and simply transform data from one representation to another. Since side effects are still required to do something useful like output to the screen or write to disk, Clojure allows side effects. But they tend to be explicit. The core data structures in Clojure are immutable, which means once they are set, they do not change. This does not mean things must remain static. To make a change, you make a copy of the original data to a new location with the required change. Loops are declared using functional iterators and recursion instead of being constructed manually with counters.
It’s a different way of thinking.

It has a very intuitive name, and the need for filtering stuff is so common in programming that I bet you correctly guessed what it is just by its name (if you didn’t know it already).
For the sake of completeness, though, let’s define it. The filter operation…wait for it…filters a sequence, returning a new sequence containing just the items approved by some criteria.
The Imperative Way
Since we’ve used employees in the previous section, let’s keep within the theme. Let’s say you need to come up with a list of the employees who have used at least three sick days.
In a more procedural style, you’d maybe write something along the following lines:
I wouldn’t say there’s something definitely wrong with this code. The method’s name is a bit too long, but it’s very descriptive. The code does what it promises. And it’s readable enough.
But similarly to the previous section, we can make the argument that the code is too noisy. We can say that, essentially, the only line that does something domain related is the if test. All the other lines are basically boilerplate-y infrastructure code. Can a functional approach help us here?
The Functional Way
Let’s rewrite the method above by using LINQ:
Here we use the “Where” extension method, passing the filtering criterium as a delegate. To be honest, the outer method became not very useful since it just delegates the work. In real life, I’d get rid of it.
Reduce is often the one many developers have some difficulty understanding. But it isn’t hard at all. Think of it like this: you have a sequence of something, and you also have a function that takes two of these “somethings” and returns one, after doing some processing.
Then you start applying the function. You apply it to the first two elements in the sequence and store the result. Then you apply it again to the result and the third element. Then you do it again to the result and the fourth item, and so forth.
The classical example of reduce is adding up a list of numbers, so that’s exactly what we’re going to do in our example.
The Imperative Way
So, suppose we’re to sum a bunch of integers.

Compare:
These kinds of constructs come up often enough when you're using functional programming, that it's a nice shortcut to have and lets you think about the problem from a slightly higher level--you're mapping against the "
That said, it's not a panacea; sometimes your function's parameters will be the wrong order for what you're trying to do with currying, so you'll have to resort to a lambda anyway. However, once you get used to this style, you start to learn how to design your functions to work well with it, and once those neurons starts to connect inside your brain, previously complicated constructs can start to seem obvious in comparison.
One benefit of currying is that it allows partial application of functions without the need of any special syntax/operator. A simple example:
Currying has the convenience features mentioned in other answers, but it also often serves to simplify reasoning about the language or to implement some code much easier than it could be otherwise. For example, currying means that any function at all has a type that's compatible with
The best known example of this is the
And an example use:
In this context,
The reason this works is because
Another, different use of currying is that Haskell allows you to partially apply type constructors. E.g., if you have this type:
...it actually makes sense to write
The "no-currying" form of partial application works like this:
A bit complicated, isn't it?
So far so nice, but more important than being simple, this also gives us extra possibilities for implementing our function: we may be able to do some calculations as soon as the
To give an example, consider this audio filter, an infinite impulse response filter. It works like this: for each audio sample, you feed an "accumulator function" (
Now here's the crucial bit – what kind of magic the function does depends on the coefficient2
But currying saves the day! We simply calculate
1 Note that this kind of state-passing can generally be done more nicely with the
2 Yes, this is a lambda symbol. I hope I'm not confusing anybody – fortunately, in Haskell it's clear that lambda functions are written with
It's somewhat dubious to ask what the benefits of currying are without specifying the context in which you're asking the question:
I used to think that currying was simple syntax sugar that saves you a bit of typing.

Editorial note: I originally wrote this post for the SubMain blog. You can check out the original here, at their site. While you’re there, have a look at CodeIt.Right, which can help you improve the quality of your code.
C# is supposed to be an object-oriented language, but it’s possible that you, as a .NET/C# developer, have been using functional programming concepts without even knowing it.
And that’s what today’s post is about. I’ll just first briefly cover the attractions of functional programming and why it makes sense to apply it even when using a so-called object-oriented language. Then I’ll show you how you’ve already been using some functional style in your C# code, even if you’re not aware of it. I’ll tell you how you can apply functional thinking to your code in order to make it cleaner, safer, and more expressive.
C# Functional Programming: Why?
We know the .NET framework offers some functional capabilities in the form of the LINQ extension methods, but should you use them?
To really answer this, we need to go back a step and understand the attraction of functional programming itself. The way I see it, the easiest path to start understanding the benefits of functional programming is to first understand two topics: pure functions and immutable data
Pure functions are functions that can only access the data they receive as arguments and, as a consequence, can’t have any side effects. Immutable data are just objects or data structures that, once initialized, can’t have their values changed, making them easier to reason about and automatically thread-safe.
Fundamental Functional Programming Operations and How to Perform Them Using C#
With the what and why of functional programming out of the way, it’s time to get to the how.
l’ll be covering three fundamental functions: map, filter, and reduce. I’ll start by showing some use cases, then I’ll show a traditional, procedural way of solving the problem. And finally, I’ll present the functional way.
In simple terms, the “map” operation takes a sequence of items, applies some transformation to each one of those items, and returns a new sequence with the resulting items. Let’s see some examples.
Suppose you wrote the following code, due to a customer’s demand:
It’s a function that adds three to each element of the given array of integers. Pretty straightforward.
Now a request for a new function comes in.

xn defined above is potentially unbound, it represents all the sequence of
xn obtained as
0, deltaX, deltaX + deltaX, deltaX + deltaX + deltaX, ... but we can set easily an upper limit in this way
We can now take the values of the
f function in each of these values simply by mapping the
xn through the function:
In the context of
Streams we can see the map application as a transformation from the sequence of $x_n$ to the sequence of $f_n := f(x_n)$.
This interpretation of the
map function applies only to sequence-like types such as Streams and Lists, but it has a very different interpretation in other types, where concepts coming from Category Theory come into place, and lead to the ideas of Monoids and Monads.
Now the only thing left to do is add up the
ynPi and multiply them by $\Delta x$, and this can easily be achieved through a
So we obtained quite simply, mapping directly the theoretical concepts down to language constructs, in 5 lines of code, a value pretty close to the real one. Consider how much verbosity and focus on the implementation details it would have taken having this implemented in Java or in any case in a procedural way. With Scala and in general with a functional approach we just focus on what we want to achieve, through which transformations, instead of focusing on the processing details. In this way we produce code that is more isolated, testable, and appliable in different contexts.

Functions (or, to be more precise, their pointers or references) can be passed as arguments to and returned from other functions. They can also be used as variables inside programs.
The code below illustrates passing the built-in function max as an argument of the function f and calling it from inside f.
>>> def f(function, *arguments): return function(*arguments) >>> f(max, 1, 2, 4, 8, 16) 16
Very important functional programming concepts are:
They are all supported in Python.
Mapping is performed with the built-in class map. It takes a function (or method, or any callable) as the first argument and an iterable (like a list or tuple) as the second argument, and returns the iterator with the results of calling the function on the items of the iterable:
>>> list(map(abs, [-2, -1, 0, 1, 2])) [2, 1, 0, 1, 2]
In this example, the built-in function abs is called with the arguments -2, -1, 0, 1 and 2, respectively. We can obtain the same result with the list comprehension:
>>> [abs(item) for item in [-2, -1, 0, 1, 2]] [2, 1, 0, 1, 2]
We don’t have to use built-in functions. It is possible to provide a custom function (or method, or any callable). Lambda functions can be particularly convenient in such cases:
>>> list(map(lambda item: 2 * item, [-2, -1, 0, 1, 2])) [-4, -2, 0, 2, 4]
The statement above multiplied each item of the list [-2, -1, 0, 1, 2] with 2 using the custom (lambda) function lambda item: 2 * item. Of course, we can use the comprehension to achieve the same thing:
>>> [2 * item for item in [-2, -1, 0, 1, 2]] [-4, -2, 0, 2, 4]
Filtering is performed with the built-in class filter. It also takes a function (or method, or any callable) as the first argument and iterable as the second.

For simple
examples like the one above, this might be a worthwhile trade-off, but in a real
application there could be vastly more time consuming operations where it would
be useful to build on the intermediate results.
It’s also worth considering that in a more complex example the smaller functions
might have more complex arguments putting a higher burden on the caller. For
this reason it’s convenient to have a single (or small group of) functions like
stats_redux to properly encode those constraints.
Eager vs. lazy evaluation
Another significant issue with the original
stats function is the eagerness
with which it evaluates. In other words, there isn’t an obvious way to compute
only some of the keys. The simplest way to solve this problem is to break down
the function as we did in the previous section, and then only manually compute
the exact values as we need them. However, this solution comes with the same set
of caveats as before:
- We lose local reuse of [potentially expensive to compute] intermediate values.
- It puts more burden on the user of the library, since they have to know and understand how to utilize the utility functions.
One possible approach to solving this problem is to manually encode the dependencies between the nodes to make it easier for the caller, but also allowing parts of the pipeline to be applied lazily:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
The above code might seem silly (because it is), but it solves the problem of
eagerness by breaking the computation down into steps that build on eachother
linearly. We also get reuse of intermediate values (such as
for free. The biggest issues with this approach are:
- It basically doesn’t work at all if the computational pipeline isn’t perfectly linear.
- It might require the caller to have some knowledge of the dependency graph.
- It doesn’t scale in general to things of arbitrary complexity.
- The steps aren’t as independently useful as they were in the previous section due to the incredibly high coupling between them.
When the source ain’t enough
The final issue I want to discuss with our (now beaten-down)
stats function is
that of transparency. In simple terms, it is extremely difficult to understand
xs is being threaded through the pipeline to arrive at a final result.

It’s all about dividing and conquering the problem by slicing it up into small bits and then figuring out what we need to do to each of the slices. Rather than identify objects, couple the data with behaviour and then deal with those objects, we pass both data and code around as required (and as easily), assembling and disassembling relationships as required.
Mind you, this is pretty much the SOP for most programming tasks, it’s just that FP makes it easier to work in this fashion. Besides, if you un-gag the Lispers for a moment, they will endlessly lecture you about the benefits of having small bits of code operate on large blobs of data. Rather like a shoal of Piranha reducing a buffalo. Be sure you re-gag them once you’re through or else they’ll never shut up.
Why spend time learning Functional Programming?
My primary reasons were:
- A New Paradigm: Learning a new programming paradigm helps to stretch your mind and makes you a better programmer overall, even if you never directly apply any of the new techniques you’ve used. Notice I’m talking about paradigms here, not languages. Learning C++ if you know Java may make you a lightly better programmer over all, but going from Procedural programming to OOP for example, can be a mind-bending experience.
- The Next Big Thing: The Functional programming weenies just can’t stop babbling about how they’re going to take over the world. And who knows, they just might. It takes a while for this sort of momentum to build up (look how long it took OOP to become mainstream!) but the signs abound; FP just might be the next big thing.
- Increased Productivity: Anecdotal evidence suggests that writing code in a functional way leads to smaller, cleaner code and fewer bugs. The logic of the algorithm is clearly detailed and many of the internal details of the operations are hidden away, leading to less clutter. I’ve often heard that FP is about describing what you want done, while Imperative Programming ends up detailing how you want it done as well.
- It’s Popping Up Everywhere!: FP isn’t all that obscure any more. You’ll regularly come across bits of functional code in various decidedly non FP languages.

Functional programming advocacy suffers from a focus on purity, where state is considered a sin to be avoided absolutely. One way the movement might make progress is to distinguish between different kinds of effects, so they could say which ones are deadly and which are venial, rather than treating all effects as indistinguishable evil. Vocabulary analogous to the assembly language programmers' “side effect” might help with this.

This note covers the following topics: O'Caml, Simple Data, Thinking Recursively, Poly-HO: Polymorphism and Higher-Order Programming, Pipelines, Datatypes, The Functional Evaluation Model, Functional Space Model, Equational Reasoning, Modules and Functors, Modular Reasoning, Mutable Data Structures and Imperative Interfaces, Threads, Locks.
Functional programming can make your head explode. This book stitches it back together. Daniel Marbach, Particular Software.
Just because they have closures and first class functions, doesn’t mean they’re functional, they’re just m. Add to Book Bag Remove from Book Bag Saved in: Functional programming languages and computer architecture: 5th ACM conference, Cambridge, MA, USA, Augustproceedings /.
Gordon A An operational semantics for I/O in a lazy functional language Proceedings of the conference on Functional programming languages and computer architecture, () Gill A, Launchbury J and Peyton Jones S A short cut to deforestation Proceedings of the conference on Functional programming languages and computer architecture, ().
Functional languages are, in my opinion, good for mainly two things: Game AIs and mathematical computations. The physics of the architecture won't allow it. In pure functional programming languages the computer can run two (or many more) functions at once because those functions are not altering outside state information.
Without further ado, here is the list of the top 8 best programming books to read if you want to set yourself apart and become a coding powerhouse. Coders at Work: Reflections on the Craft of Programming >> purchase on Amazon. If you’re curious about life as a programmer than Coders at Work is the book.
The functional program is the “pre-architectural programming” information that tells the architect how to create the archi - tectural program for the building. The time to make a decision about how food will be prepared and served, how laundry.
It is an alternative way of creating programs by passing application state exclusively through functions. By avoiding side effects, it's possible to develop code that's easy to understand.
This page is powered by a knowledgeable community that. Functional programming is about defining functions and organizing the return values of one or more functions as the parameters of another function. Functional programming languages are mainly based on the lambda calculus that will be discussed in Chapter 4.
Typical functional programming languages include ML, SML, and Lisp/ Size: KB.

Revision as of 06:20, 20 July 2010
Turning free variables into arguments.
As an example, consider the following worker wrapper function, which computes the truncated square root of an integer:
isqrt :: Integer -> Integer isqrt n | n < 0 = error "isqrt" | otherwise = isqrt' ((n+1) `div` 2) where isqrt' s | s*s <= n && n < (s+1)*(s+1) = s | otherwise = isqrt' ((s + (n `div` s)) `div` 2)
isqrt :: Integer -> Integer isqrt n | n < 0 = error "isqrt" | otherwise = isqrt' n ((n+1) `div` 2) where isqrt' n s | s*s <= n && n < (s+1)*(s+1) = s | otherwise = isqrt' n ((s + (n `div` s)) `div` 2)
The isqrt' function may now be safely lifted to the top-level.
Naive lambda lifting can cause a program to be less lazy. Consider, for example:
f x y = g x + g (2*x) where g x = sqrt y + x
f x y = g y x + g y (2*x) where g y x = sqrt y + x
f x y = let sy = sqrt y in g sy x + g sy (2*x) where g sy x = sy + x
An expression of this sort which only mentions free variables is called a free expression. If a free expression is as large as it can be, it is called a maximal free expression, or MFE for short. Note that
f x y = let psy = (+) (sqrt y) in g psy x + g psy (2*x) where g psy x = psy x
However, you save no more work here than the second version, and in addition, the resulting function is harder to read. In general, it only makes sense to abstract out a free expression if it is also a reducible expression.

A transducer that maps elements from a to b therefore transforms a step function on b‘s to a step function on a‘s
The statelessTransducer function takes as argument a function from a step function to a new step function. Yet, our mapping function is defined in terms of a function taking three arguments:
To understand this, we need just need to substitute the second occurrence of the type alias Step inside the prototype of the function onStep given to statelessTransducer:
Put differently, the type of onStep correspond to a step function that takes an additional parameter as first argument: the next step function in the pipe-line. Hence the three arguments to mapping.
Note: pragmatically, there is not much a stateless transducer can do with this next function except calling it once (mapping), several time (concat mapping) or not calling it (filtering). It still allows to build interesting transformations as the next section will show.
Using this helper function, we can define stateless transducers in a very few lines of code.
For instance, we can define takingWhile, which consumes a source of data as long as its element satisfy a given predicate. The definition is short and quite close to the specification of what the transformation does:
Here is a quick example of how it can be used to consume a stream of values lazily:
Note: interestingly, while we can define takingWhile as a stateless transducer, you cannot define droppingWhile (which ignores elements until one that satisfies the predicate is encountered) without tracking some state.
Toward stateful transducers
We defined transducers as arbitrary transformation on reducers, taking as input a reducer and returning as output a potentially completely different reducer.
In practice, the transformation is not as arbitrary as this may sound: a lot of transformation do not make sense. We can therefore offer some helper functions that will help us define more easily a reduced set of transducer that we will call sound transducers.
In this section, we will define these helpers function to use them in the next section. If you need examples to make sense of these functions, try to switch back and forth between this section and the next one.
Characterising sound & unsound transducers
A sound transducer is one that performs only additive changes to the reducer it acts upon. It might add some state but will not remove or modify any existing one. It might add a completion step but will not remove or impact existing ones.

For the past two years, my day-to-day programming language has been Scala. Scala is a hybrid language that combines the approaches of object-orientation and functional programming. You can treat Scala as a “Java.next” with minimal changes in your object-oriented mindset (the only thing that springs to mind is that Scala’s “companion objects” might seem like unnecessarily clunky replacements of Java’s “static” functionality). Even just as a drop-in replacement, I think most programmers would prefer Scala to Java: type inference saves finger-typing, and fields and class structure are a little clearer.
Scala is also a functional programming language. I’ve talked about functional programming many times over the years, but it continues to have an undeserved air of mystery around it. The low bar for a language to be “functional” is the support of functions as “first-class constructs.” Essentially, wherever you can have a value (on the right-hand of assignments, as the input or output of functions, etc.), you can have instead an anonymous block of code (if you like Greek, you can call them “lambda functions”). This turns out to be so convenient that every mainstream language either already supports or is moving toward such support; every language is, or will be soon, a “functional programming” language.
The greatest practical benefit of first-class functions is that, multiple times per day, instead of writing a for loop that iterates over elements of a collection to transform, filter or accumulate something, you just pass a small function to common collection-class functions such as (in the Scala world), map, filter and foldLeft. I cannot imagine a programmer not preferring the use of such functions: They are both clearer and more concise than loops.
Mutable state is when, after having been assigned a value once, a variable is reassigned a value. In a loop, for instance, the index variable is constantly reassigned. In a Lightbulb object, one might have a mutable isOn field that is reassigned in a switch() function. In a more functional program, you don’t have explicit index values (using, instead, higher-order and recursive functions to manipulate collections), and objects have few fields (a Lightbulb class wouldn’t have a switch() function but only on() or off() ).

So, for the benefit of the uninitiated who happened to accidentally stumble upon my obscure and randomly technical blog, I’ll give the lowdown on Functional Programming … in my own words. Apart from the regular differences between Functional and Imperative programming, here’s my experience with it:

Because data structures are immutable by default, sharing state and avoiding locks is way much easier.
Although it is a functional language at heart, F# does support other styles which are not 100% pure, which makes it much easier to interact with the non-pure world of websites, databases, and other applications. In particular, F# is designed as a hybrid functional/OO language, so it can also do everything that C# can do. Obviously, F# is still part of the .Net ecosystem, with seamless access to all third party .NET libraries and tools. It runs on most platforms, including Linux, Android, and IOS (via Mono).
A Trivial code example to whet our appetite:
Let’s try to sum up all the squares from 1 to a specified number N using C# at first and then F#
C# ‘Normal’ Implementation:
We will not dissect the code at this stage, but the example should be enough to immediately show some benefits gained e.g. in conciseness.
When you start to think functionally, you will be able to improve your code in even C# and for the same above code you will implement it as follows:
C# ‘Functional’ Implementation:
Still, we can see that F# wins even against C# as functional, and be rest assured, it wins in many vital scenarios, to be explored in the next series of blogs.
We will explore “how to think functionally,” which is very different from thinking imperatively and will gracefully introduce the functional concepts below with gradually relevant code examples on how they can improve even your C# based solution designs.
• Partial application
• First-class functions
• Higher-order functions
• Function pipelines
• Function composition
• Map, filter, and reduce
• Continuation passing style
• Monads (computation expressions)
These are very important building blocks that will make your functional programming journey very easy when fully understood. Consecutive weekly blogs will dissect every concept individually, and if you are itching to see more code examples, that would be the right time to get our hands dirty.
Author: Kenneth Fukizi – Lead Analyst Consultant

You can easily create your own parametrized transducers with “partial”, so that you capture all parameters but “xf”:
One of the best things abut transducers is that they are composable; you can create a new transducer out of a set of existing ones.
This is more efficient than mapping/filtering over multiple sequences in turn.
See how B was applied first, and then A.
Putting it all together - separating text paragraphs
We want to create a transducer that receives a sequence of lines (maybe over a core.async channel) and separates them into paragraphs.
This is a typical stateful transducer, and something that we cannot do easily with just map and filter.
In this case it is important that if we have open stanzas when the sequence terminates, we reprocess them (see A, and see it’s the very same thing we’re doing in B) and then we generate the final result, that will in turn be sent down the pipeline (C).
This is pretty cool, as a lot of problems can be expressed in a way that is similar to this; and IMHO this alone makes transducers worth learning.
But the very best thing about transducers is…..
The really best thing about transducers is that (often) you don’t need to write them. If you had to write transducers from scratch every time like in the examples above, they would be still be cool, but in 99% of the cases you would prefer the old map/filter/reduce - it might not be as efficient or powerful, but is concise and compact and easy to read.
Truth is that you can have the best of both worlds - you can use your classic friends map&co. and use transducers. This is because many functions in core that used to have a collection as their last parameter now have an arity that produces a transducer by just omoiiting that collection. So if you say:
you get a transducer for free.

Well, we can define a few more core helper functions:
/// Duplicate the top value on the stack let DUP stack = // get the top of the stack let x,_ = pop stack // push it onto the stack again push x stack /// Swap the top two values let SWAP stack = let x,s = pop stack let y,s' = pop s push y (push x s') /// Make an obvious starting point let START = EMPTY
And with these additional functions in place, we can write some nice examples:
START |> ONE |> TWO |> SHOW START |> ONE |> TWO |> ADD |> SHOW |> THREE |> ADD |> SHOW START |> THREE |> DUP |> DUP |> MUL |> MUL // 27 START |> ONE |> TWO |> ADD |> SHOW // 3 |> THREE |> MUL |> SHOW // 9 |> TWO |> SWAP |> DIV |> SHOW // 9 div 2 = 4.5
But that's not all. In fact, there is another very interesting way to think about these functions.
As I pointed out earlier, they all have an identical signature:
Stack -> Stack
So, because the input and output types are the same, these functions can be composed using the composition operator
>>, not just chained together with pipes.
Here are some examples:
// define a new function let ONE_TWO_ADD = ONE >> TWO >> ADD // test it START |> ONE_TWO_ADD |> SHOW // define a new function let SQUARE = DUP >> MUL // test it START |> TWO |> SQUARE |> SHOW // define a new function let CUBE = DUP >> DUP >> MUL >> MUL // test it START |> THREE |> CUBE |> SHOW // define a new function let SUM_NUMBERS_UPTO = DUP // n >> ONE >> ADD // n+1 >> MUL // n(n+1) >> TWO >> SWAP >> DIV // n(n+1) / 2 // test it START |> THREE |> SQUARE |> SUM_NUMBERS_UPTO |> SHOW
In each of these cases, a new function is defined by composing other functions together to make a new one. This is a good example of the "combinator" approach to building up functionality.
We have now seen two different ways that this stack based model can be used; by piping or by composition. So what is the difference? And why would we prefer one way over another?
The difference is that piping is, in a sense, a "realtime transformation" operation.

- Philip Wadler, another father of Haskell, was one of the implementors of generics in Java.
- Martin Odersky, the father of Scala, that adapted a lot from Haskell, was also involved in the implementation of generics in Java.
- Erik Meijer is a passionate admirer and researcher around Haskell. He used the Haskell concepts of monads and created the well know C# library LINQ.
I will even go one step further. How knows functional programming and in particular Haskell, know, how the mainstream programming languages will develop in the next years. Even a pure object-oriented language like Java can not withstand the pressure of the functional ideas. Java has now generics and lambda expressions.
But now back to my subject. What are the characteristics of functional programming languages?
On my search for the functional characteristics, I identified seven typical properties. These must not be all characteristics and each functional programming language has not to support them. But the characteristics helps a lot to bring meat to the abstract definition of functional programming.
The graphic gives, on one hand, the characteristics of functional programming and gives, on the other hand, the outline of my next posts. I will provide a lot of examples in Haskell, C++, and Python. But what do the seven characteristics mean?
First-class Functions are typical for functional programming languages. These functions can accept functions as an argument or return functions. Therefore, the functions have to be higher-order functions. That means, they behave like data. Pure functions always return the same result when given the same arguments and can not have a side effect. They are the reason that Haskell is called a pure functional language. A pure functional language has only immutable data. That means, they can not have a while or for loop which is based on a counter. Instead of the loops, they use recursion. The key characteristic of functional programming is that you can easy compose functions. This is because of their bread and butter data structure list. If an expression evaluates its arguments immediately, it's called greedy or eager evaluation. If the expression evaluates the arguments only, if needed, it's called lazy evaluation. Lazy evaluation will reduce time and memory if the evaluated expression is not needed. I think, you already guess it. The classical programming languages are greedy. They evaluate their expressions immediately.
I start in my next post with first-class functions. We have them since the beginning of C++.

I’m a regular at http://programming.reddit.com and just about every day there’s at least one (or two or three) posts about some functional programming language or the other. Usually it’s Haskell which is being showcased, though you’ll also find entries for Erlang and occasionally for some of the more obscure ones like O’Caml or Dylan. I finally zoned out under the constant barrage of propaganda and moaning softly (“brains! braaaaiiiiins!) zombie-shuffled over to check out what the fuss was all about.
What’s all this about Zen then?
The Zen of programming is when you internalise the correct way of solving a problem using the programming model you’re working with. You might start off programming with something like C, using it in a classic procedural fashion. When you move from Procedural Programming on to something like Object Oriented Programming (OOP) using Java or C++ etc., it’s a bit of a culture shock at first. You keep trying to program procedurally, fighting the language every step of the way. There finally comes a moment however, when all the abstract concepts behind OOP fall into place with an almost audible snap and suddenly, in a moment of epiphany, you attain OOP enlightenment.
Now I can’t say I’ve achieve that level of union with the Tao of Functional Programming, but I am starting to finally grok what the whole thing is about. However, all opinions listed below are subject to rather radical change!
What’s Functional Programming (FP)?
I’ll save me some time and copy-paste in some definitions.
Functional programming is a style of programming that emphasizes the evaluation of expressions, rather than execution of commands. The expressions in these language are formed by using functions to combine basic values. A functional language is a language that supports and encourages programming in a functional style.
-- FAQ for comp.lang.functional
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 with the imperative programming style that emphasizes changes in state.
As far as I can make out so far, FP is all about decomposing the problem down to the various algorithms and data transformations involved and then cleanly enumerating them. We don’t really need to worry about the ‘objects’ involved (there aren’t any), or their relationship with one another.

In a short time, functional programming went from an obscure academic endeavor to the technology "du jour" of the software industry. On the one side, this is great, because functional programming holds real promise to simplify the construction of highly reliable software. On the other hand, it is also frightening because the current hype might lead to over-selling and sometimes too uncritical adoption of concepts that have not yet been sufficiently validated in practice. In particular I see with worry the trend to over-abstract, which often leads to cargo-cult technology.
In this talk I give my opinion of what the core of functional programming is that we can and should use today, why that core matters, and where we currently face challenges. I argue for combining functional programming with the principle of least power, for eschewing fancy abstractions, and for being modest in what we can and should express in our programs. I also show how some of these approaches are reflected in our work on the next version of Scala.
Martin Odersky is the inventor of the Scala language, a professor at EPFL in Lausanne, Switzerland, and a founder of Lightbend. His work concentrates on the fusion of functional and object-oriented programming. He believes the two paradigms are two sides of the same coin, to be unified as much as possible. To prove this, he has worked on a number of language designs, from Pizza to GJ to Functional Nets. He has also influenced the development of Java as a co-designer of Java generics and as the original author of the current javac reference compiler.

Look how we return “result” as-is if we do not want to change it, while we “return” values by calling xf with a (new) intermediate value.
There are a few simple ways to “run” transducers:
into: as the vanilla version does, appends to an existing collection the transducer applied to a collection
transduce: applies transducer to a collection, and then using a “reducing” function to create our final result
sequence: returns a new sequence by applying the transducer to a sequence. This sequence is lazy, so if it’s not needed, it’s not computed either.
educe: captures the transduction process into a function.
Note that as you have no idea of how many items of the source sequence need to be consumed to produce your final sequence, there is no 1:1 equivalence.
As we said above, you can return 0 or more values from a transducer:
- To return no new values, just return “result” as it is
- To return one value, return “(xf result value)”
- To return multiple values, just call “(xf result value1)”, then “(xf result value2)”, and so on.
To show how thos works, this transducer duplicates odd values and removes even ones:
Having the ability to control when a value is emitted is especially important for trasducers that must keep track of a current (inner) state.
Our transducer will return a sequence of odd numbers intertwined with their unique sequence number for each item in our sequence, starting from 100 onwards (we count all numbers for a change).
To do this we use an atom (or possibly a transient) that we use as a keeper of current state. See how this atom is unique per function invocation, so it’s local mutable state (and how this starts to look a bit like an “object” encapsulating state).
Of course, a stateful transducer depends on its internal state and is not inherently parallelizable if run in parallel, so beware!
Transducers as reducers
You can easily turn a stateful transducer into a reducer, just like this:
See how we basically ignore result and use a result of our own making at the end of the eduction.

R3-Alpha's CLOSURE provided two things. One was a unique identity for the words of a function's arguments and locals for each recursion. This is what I've called "specific binding" and now comes "for free" in all functions...so you don't even have to think about it. (It's not exactly free, but we can hope it will converge to "very low cost".)
So in Ren-C:
>> foo: function [x code] [ append code [print x] if x > 0 [ probe code do code foo (x - 1) code ] ] >> foo 2  [print x] 2 [print x print x] 2 ;-- R3-Alpha FUNCTION! got 1, only CLOSURE! got 2 1
Users can now take that for granted.
But what I want to talk about is the other emergent feature of R3-Alpha CLOSURE!. This was that if an ANY-WORD! that was bound to the arguments or locals "escaped" the lifetime of the call, that word would continue to have its value after the function ended...for as long as references to it existed.
>> f: closure [x] [return [x]] >> b: f 10 == [x] >> reduce b
Functions did not do this:
>> f: function [x] [return [x]] >> b: f 10 == [x] >> reduce b ** Script error: x word is not bound to a context
It goes without saying that the closure mechanic is going to cost more, just by the very fact that they need to hold onto the memory for what the word looks up to. But the way things work today, it doesn't just need to hold onto that cell of data...it holds onto all the args and locals of the function. (R3-Alpha was more inefficient still...it not only kept the whole frame of values alive, it made a deep copy of the function body on every invocation of that function...so that the body could be updated to refer to that "frame". Specific binding lets Ren-C dodge that bullet.)
Now and again, the "keep-things-simple" voice says that the system would be simpler and faster if all executing frames (and their frame variables) died after a function ended. If you wanted to snapshot the state of a FRAME!

This makes it easy to build simple parsers. You can see how this is done by reading my post about parser generators where I build a simple four-function expression parser.
When using parser combinators, parsers are built up by composing (combining) other parsers using various combining operators (combinators). The result of one of these combining operators is another parser. Eventually, you build up a top-level parser that can parse your entire grammar. Then you invoke that parser on your input stream to parse the input.
These parser combinators are monads. See "Monadic Parser Combinators".
Uniform Container Methods in ScalaThe
Optionclass, mentioned above, defines methods for
filter. All of the container classes in Scala, including
Maptrait, define these same three methods. The container classes also implement
foreach, even though it never has more than one item. This makes more sense if you think of
Listthat can have only zero or one element in it.
Having this same set of methods available for all of the collection classes makes it easier for the programmer to use any of them, but it also makes it possible to write a package of higher-level control code that can accept any of these classes. With such a higher-level package, you can add your own container class that will work with that package as long as your container class supplies the appropriate set of methods.
The container classes in Scala (including
Option) are all monads. Because all monad classes supply a specific set of methods (informally, the monad interface), a monad library of higher-level control classes can be written that use that monad interface. In addition to supplying specific methods, there are a couple of consistency rules that constrain how those monad methods must behave. This is no different than, for example, the contract in Java relating the behavior of the
hashCodemethods for a class. As with any other interface definition and contract, if you write your own class and it implements the monad methods and follows the monad contract, then you can use that class with a monad library.
Functional LanguagesFunctional languages stress some things that are not typically discussed in imperative languages such as Java:
- Referential transparency
- Immutable data
- Recursion rather than loops
- Lazy evaluation
Referential TransparencyA pure functional language, such as Haskell, has no side effects. This means that calling a function returns a value and does nothing else.

As mush as FP has done, in the end, all our programs are structured. That is, it doesn't matter how pure or functional we make a them - they are always translated to assembly, so what actually runs ...
I've been told in previous questions that functional programming languages are unsuited for dynamic systems such as a physics engine, mainly because it's costly to mutate objects. How realistic is ...
I was wondering about the origins of the "let" used in Lisp, Clojure, and Haskell. Does anyone know which language it appeared in first?
I'm mainly a .NET developer so I normaly use Windows/VisualStudio (that means: I'm spoiled) but I'm enjoying Haskell and other (mostly functional) languagues in my spare time. Now for Haskell the ...
If data is simple and objects are complex, I'm curious if there are any existing statically typed languages that would be able to augment(?) a map type into a type with guaranteed fields. I realize ...
Functional languages, by definition, should not maintain state variables. Why, then, do Haskell, Clojure, and others provide software transactional memory (STM) implementations? Is there a conflict ...
One of the major advantages of software transactional memory that always gets mentioned is composability and modularity. Different fragments can be combined to produce larger components. In ...

I remember the day I got the mind shift about functional programming. I switched from being a fervent defender of Java and C# to a passionate of LISP dialects. At the time I was convinced that there were nothing better than OOP and curly bracket syntaxes. I was then fighting for conventions and simplicity rather than language expressivity.
- Why do not C and C++ have a module system ?
- Why do not have C and C++ a garbage collector ?
- Why C does not have namespaces ?
- Why C does not have safer string and array primitives ?
- Why aren’t Unicode/UTF-8 strings the default in C and C++ ?
- Why are the C and C++ libraries naming convention so bad ?
- Why is C++ so complex?
As a good ignorant I thought that languages evolved with the time, and that these problems were not addressed because nobody thought about them before. And I discovered LISP the second oldest programming language with none of these problems and even powerful features other languages don’t have such as macros or continuation capture. I got interested in functional programming languages and I learned Haskell, CAML, and finally F#.
I don’t know why but the concept of sequences in functional programming languages amazed me.
How do you perceive infinity?
I never thought about it before, since resources on a computer are finite. But interesting question, let say I want to represent the infinite sequence of numbers, what characterizes this infinity and makes it exist? Is it the fact that these numbers are all present in the computer memory at the same time (which is impossible) or the fact that I can get one of them when needed.
How could we possibly define the infinite sequence of natural integers?
Starting from 0 we can recursively define these numbers just by adding one, however this recursion shouldn’t take place until needed, so that the whole number sequence is never in memory. There is no choice that to delay the evaluation of the recursion building the sequence. We could take advantage of the fact that list are pairs, the car of the pair would be a value and the cdr of the pair a delayed evaluation leading to a pair. Delaying a computation, it’s when laziness comes into play.
What is laziness?
Wikipedia: “Laziness (also called indolence) is a disinclination to activity or exertion despite having the ability to do so.

For instance, we could define an add3 function which nefariously does the wrong thing when the user inputs 7.
fun add3(7) = 2 | add3(x) = x+3
The vertical bar is read “or,” and the idea is that the possible cases for the function definition must be written in most-specific to least-specific order. For example, interchanging the orders of the add3 function cases gives the following error:
- fun add3(x) = x+3 = | add3(7) = 2; stdIn:13.5-14.16 Error: match redundant x => ... --> 7 => ...
Functions can call themselves recursively, and this is the main way to implement loops in ML. For instance (and this is quite an inefficient example), I could define a function to check whether a number is even as follows.
fun even(0) = true | even(n) = not(even(n-1))
Don’t cringe too visibly; we will see recursion used in less horrifying ways in a moment.
Functions with multiple arguments are similarly easy, but there are two semantic possibilities for how to define the arguments. The first, and simplest is what we would expect from a typical language: put commas in between the arguments.
fun add(x,y) = x+y
When one calls the add function, one is forced to supply both arguments immediately. This is usually how programs are written, but often times it can be convenient to only supply one argument, and defer the second argument until later.
If this sounds like black magic, you can thank mathematicians for it. The technique is called currying, and the idea stems from the lambda calculus, in which we can model all computation using just functions (with a single argument) as objects, and function application. Numbers, arithmetic, lists, all of these things are modeled in terms of functions and function calls; the amazing thing is that everything can be done with just these two tools. If readers are interested, we could do a post or two on the lambda calculus to see exactly how these techniques work; the fun part would be that we can actually write programs to prove the theorems.
Function currying is built-in to Standard ML, and to get it requires a minor change in syntax. Here is the add function rewritten in a curried style.

Or maybe it is a sequence of transformations, a sequence of expressions that transform some data? But then what is data, can a program transform itself without any data, can it move by itself without a problem to be solved? Maybe there are different ways of building programs, different ways we can describe the steps in play, like different perspectives, frames of reference, maybe some computations are described as abstract structures in time and space, while others are described as a sequence of commands that build these structures. How do we tell the difference? Take a moment and really ponder, how does a program look like, is program just to which we give something to solve, just to encode some business problem, publish a website, or is there something deeper within, a notion of self-replicating awareness that keeps on calculating, surprising us, interacting with us, with our environment?
Haskell is a functional programming language, pure and lazy, statically typed language. It is a functional language because programs written or coded in Haskell are more than just a sequence of steps to be carried out, they are formed out of pure expressions, pure functions, functions that operate on a total space, functions that produce other functions, functions that create larger structures of functions, like a self replicating machine, like an infinity mandala, Haskell programs are beautiful mathematical abstract entities. When we say mathematical we mean symmetrical, we mean there is an underlying logic within them, that can be proofed, that can be mapped, applied, like an empty variable to any outside thing or a process we know. Functional programs do not destructively update the state of the program, they make copies of themselves when we change them, and so we can track and observe how they evolve through time, and so they consume the space of computations.
Let's begin with a simple program, with a simple expression. Let's write a number, because numbers are simple, meaning numbers are something which is common to many of us all, we count things, we count fingers, we have two eyes, we have basic understanding of a numberness of some sort. It makes no difference whether we are great or not at math, just think of a number, any number you like. Good.
For instance, let's write the number two,
2. We have a symbol
2 representing some abstract quantity, an abstract context, I am saying abstract because we do not know what the number two represents, two of which, two of what.

Function parameters do most of the work that variables do in dysfunctional programming.
As we don't have variables we don't need loops and recursion plays the role of iteration and parameters play the role of loop variables.
OK, but what is this "tail recursion"?
Well if you can arrange your recursive functions so that the call to the next function occurs right at the end of the function i.e. in the tail then the function can be optimized by the compiler into a loop.
Yes that's right - you go to the trouble of thinking recursively and the compiler undoes it all and re-writes it as a loop.
The reason that this can be done is that as soon as the tail of the function is reached the compiler can throw away all of the state information about the function, i.e. its stack frame, and treat the new call as part of the same function call. That is it unwinds:
into something like:
let total=0+(0+1)+(1+1)+(2+1)+(3+1)+(4+1) ... +9
With tail recursion optimization functional languages are as efficient as dysfunctional languages.
There are lots of other related mechanisms for putting off binding a value to a symbol until the value is completely determined but they all have a similar feel and use the same sort of techniques.
Perhaps the most notorious of all functional programming mechanisms for getting things done that are natural in dysfunctional languages is the monad.
To explain the subtleties of the monad would take another article, but what you really need to know is that the monad puts the sequence of operations idea back into functional programming. Monads provide the facilities to implement side effects, I/O, variable assignment and so on in a way that looks static - unless you look very carefully that is.
So is all of this just magic for the dysfunctional programmer to worry about?
Well yes - and no.
It is sadly true that functional programmers have a tendency to use math - category theory in particular - to make simple ideas seem very much more sophisticated.
You need to always keep in mind that programming is essentially practical and hence cannot be as complicated as abstract mathematics.
However there are times when functional programming just seems right. There is also no doubt that some of the tools of functional programming are hard to give up once you have experienced their advantages.
For example, every programming language should have first class and higher functions - it just makes things so much simpler and so much more powerful.

(2019) argue that the two notions are incompatible in the context of System F, where sealing is transparently driven by potentially imprecise type information, while New et al. (2020) reconcile both properties at the cost of abandoning the syntax of System F and requiring user-provided sealing annotations that are not subject to graduality guarantees. Furthermore, all current proposals rely on a global form of dynamic sealing in order to enforce parametric behavior at runtime, which weakens parametric reasoning and breaks equivalences in the static language. Based on the observation that the tension between graduality and parametricity comes from the early commitment to seal values based on type information, we propose plausible sealing as a new intermediate language mechanism that allows postponing such decisions to runtime. We propose an intermediate language for gradual parametricity, Funky, which supports plausible sealing in a simplified setting where polymorphism is restricted to instantiations with base and variable types. We prove that Funky satisfies both parametricity and graduality, mechanizing key lemmas in Agda. Additionally, we avoid global dynamic sealing and instead propose a novel lexically-scoped form of sealing realized using a representation of evidence inspired by the category of spans. As a consequence, Funky satisfies a standard formulation of parametricity that does not break System F equivalences. In order to show the practicality of plausible sealing, we describe a translation from Funk, a source language without explicit sealing, to Funky, that takes care of inserting plausible sealing forms. We establish graduality of Funk, subject to a restriction on type applications, and explain the source-level parametric reasoning it supports. Finally, we provide an interactive prototype along with illustrative examples both novel and from the literature.
While many mainstream languages such as Java, Python, and C# increasingly incorporate functional APIs to simplify programming and improve parallelization/performance, there are no effective techniques that can be used to automatically translate existing imperative code to functional variants using these APIs. Motivated by this problem, this paper presents a transpilation approach based on inductive program synthesis for modernizing existing code. Our method is based on the observation that the overwhelming majority of source/target programs in this setting satisfy an assumption that we call trace-compatibility: not only do the programs share syntactically identical low-level expressions, but these expressions also take the same values in corresponding execution traces.

Guest author Pete Libman writes:
You are sitting at your screen wearing a t-shirt with some witty clever tech joke on it, reading some blog written by a bloke who probably looks a lot like the guy from the comic shop in The Simpsons.
Monolithic databases are so 80s, inflexible, they are an obstacle to change. Referential integrity stops us implementing service orientated architecture, and they cannot be harmonised with continuous delivery.
Do you agree?
I have made a discovery. You might think it’s obvious, but it was new to me. It was this: that programmers come in different shapes and sizes.
When was the last time you read through someone else’s code, not because you were looking for a snippet to pinch or because you’ve been saddled with debugging it; but for the sheer joy of reading someone else’s elegant, witty, creative code?
Modern computer systems couldn’t function without it, and it’s at the heart of nearly every modern software development. And yet, the very mention of its name is enough to strike terror into the hearts of even hardened developers. Why is multi-threading so difficult?
For more than thirty years, alongside conventional language development, there’s been a small but thriving culture of functional languages. These are not like the languages we all know and love. Their most obvious property is that they contain no variables at all; instead, they describe truths about the problem to be solved.
As anyone with even a passing familiarity with functional programming knows (and I accept that passing familiarity usually comes only after three to five years), things in a functional language don’t do anything (the way procedures execute or variables change in conventional languages); instead they are something, and what they are never changes. A term may describe a function which defines a list of primes, or it may describe what it means to be an expression, or what-have-you. But whatever it is, it describes it once and for all time – the function is the list of primes, it’s not a sequence of operations to compute the list.
Proponents of functional languages claim that by talking exclusively in terms of values, you get shorter, simpler, and more reliable programs. If things are things, rather than do things, they reason, then if they ever work, they’ll always work. If nothing ever changes, where can a bug hide?

My colleague recently wrote an excellent post discussing the functional and object-oriented paradigms. As someone who comes from a functional programming background, I definitely agreed with one thing: We need to stop building arbitrary walls that prevent us from learning from and helping each other.
The post made me dig deep down within myself and really consider why I love functional programming so much.
In essence, the functional and object-oriented paradigms stem from different concepts about how the world works. They represent different opinions about how to best model the world while we are writing programs.
The object-oriented paradigm models everything as an object. These objects can then interact with each other and thereby update their internal state when something in the system changes. This corresponds to how we often conceptualize the world, for instance, by modelling a computer mouse as an object whose position on a screen changes over time.
The functional programming paradigm takes a different approach. The behavior of the system is modelled using pure functions and these are strictly separated from the actual data within the system, which is modelled with immutable values. This is based on the mathematical perspective that a value itself cannot change (i.e. the coordinates
x,y are constant) and all changes in the system are actually the application of a function (i.e. the movement of a mouse can be represented with a function that takes the coordinates
x,y and produces new coordinates
The question then remains: Which approach is better?
My answer: This is the wrong question.
I personally have been very influenced by Rich Hickey’s video about Simplicity. We as humans are not very good at understanding or comprehending multiple things at any given time. We can follow one idea or concept, but as soon as multiple ideas or concepts come into play we easily lose our focus and get confused.
Simplicity is key to creating and maintaining good software. Even when programming a small web application, it is not possible to examine every part of the software at any given time. Instead, we begin inspecting the software and try to figure out the behavior of the application step by step. A point in the program where unrelated concerns are mixed together ‘complects’ the entire program and thereby makes it more complex. By attempting to remove or minimize these positions in our program, we increase the simplicity of the application and make it easier to maintain in the future.
Simplicity is not easy.
It is easy to write down the first thing that pops into your head.

POPL is the premiere conference on the theoretical foundations of programming languages. The PC Chair, General Chair, and Steering Committee Chair of POPL 2020 review this year’s event.
An impressive number of transformations in both compilers and in ordinary programming are special cases of a transformation called “defunctionalization.” This post explains what it is and the many places it’s useful.
Runtime Support for Multicore Haskell (ICFP’09) was awarded the SIGPLAN ten-year most-influential paper award in 2019. In this blog post we reflect on the journey that led to the paper, and what has happened since.
We accept that data structure determines program structure. But we should not forget that it is not just the input data that may be structured: output data may be structured too, and both may determine program structure.

Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment
We can modify lists by appending them new elements, but when we try to do this with tuples, they are not changed but new instances are created:
>>> # Lists (mutable) >>> a = [1, 2, 4] # a is a list >>> b = a # a and b refer to the same list object >>> id(a) == id(b) True >>> a += [8, 16] # a is modified and so is b - they refer to the same object >>> a [1, 2, 4, 8, 16] >>> b [1, 2, 4, 8, 16] >>> id(a) == id(b) True >>> >>> # Tuples (immutable) >>> a = (1, 2, 4) # a is a tuple >>> b = a # a and b refer to the same tuple object >>> id(a) == id(b) True >>> a += (8, 16) # new tuple is created and assigned to a; b is unchanged >>> a # a refers to the new object (1, 2, 4, 8, 16) >>> b # b refers to the old object (1, 2, 4) >>> id(a) == id(b) False
Advantages of Functional Programming
The underlying concepts and principles — especially higher-order functions, immutable data and the lack of side effects — imply important advantages of functional programs:
- they might be easier to comprehend, implement, test and debug,
- they might be shorter and more concise (compare two programs for calculating the factorial above),
- they might be less error-prone,
- they are easier to work with when implementing parallel execution.
Functional programming is a valuable paradigm worth learning. In addition to the advantages listed above, it’ll probably give you a new perspective on solving programming problems.

Learning functional programming made me a 10x better developer. It helped me learn how write code that is clean, easy to maintain, and scalable.
This is especially important in this day and age where software applications keep getting more complicated. The days of building and maintaining a simple web app are over.
As a developer, the expectations set upon you are higher than ever. It now falls on our shoulders to build, test, maintain, and scale complex applications that impact millions of people daily. This can be especially daunting as a beginner because we’re just getting the hang of writing code that actually works, let alone writing code that is easy to understand, write, debug, reuse, and maintain.
This is where Functional programming made a difference for me—it helped me learn how to code that is easy to understand, write, debug, reuse, and maintain. As a result, I feel much more confident in my coding abilities.
Even if you are not using a functional programming language at work or on your side projects, knowing the basics of functional programming equips you with a powerful set of tools to write better code.
In my new e-book, I’ll teach you the basics of functional programming so that you have all the foundational knowledge you need to apply the principles at work, in your next job interview, or on your next side project.
The rest of the post will give you a simple explanation of what functional programming is, which you’ll need to know before diving into the e-book. ?
Let’s get right into it! ?
What is functional programming?
So. What is “functional programming,” exactly?
Functional programming isn’t a framework or a tool, but a way of writing code. In functional programming, we place a major emphasis on writing code using functions as “building blocks.”
Your program is defined in terms of one main function. This main function is defined in terms of other functions, which are in turn defined in terms of still more functions — until at the bottom level the functions are just language primitives like “number” or “string.”
If you’re reading this thinking, “Hmm, but wait? Doesn’t every language use functions to write code?” then good ?. It means you’re paying attention.
You’re right — every programming language has functions. But functional programming takes it to a whole ‘nother level ?
To understand what I mean, let’s rewind and start with the basics.

You are a programmer and one of the greatest struggles you face every day is confronting yourself from yesterday. You have to deal with your reflection from the past, when everything made perfect sense, but today not so much anymore. An abstraction developed seemed like a perfect fit for the problem at hand, doing exactly what was needed, but perhaps without realizing it is doing much more than this. It was tempting to use this power and at the time it appeared justified. Today there is a bug,
"And you won't understand why You'd give your life You'd sell your soul But here it comes again, Too much power will kill you every time."
For a while I used to be an imperative programmer. In the imperative programming world, type systems do not play that important role. As a consequence, if one attempts to understand what a function taking a unit value and returning a unit value does just by looking at its type signature, they might not get far. Sure, it is an identity function, but it is allowed to do all kinds of side effects too. In the imperative programming world, this function can print to the console, delete records in a database, fetch data over the network, and it can do anything else that comes to your mind. The only chance of understanding what such a function really does is to read it completely, and recursively do the same for every function it calls.
For three years now I have been a functional programmer in Haskell. In a typed functional programming world with effects and function totality, type systems play an important role. As a consequence, if one attempts to understand what a function taking a unit value and returning a unit value does just by looking at its type signature, they can safely conclude it can only return a unit value and do nothing else. At first, that seems like a big reasoning win over the imperative programming world. However, in Haskell the IO monad is so pervasive that almost every effectful function is expressed directly or indirectly (via the
MonadIO class) in the IO monad. In such a functional programming world, this function can print to the console, delete records in a database, fetch data over the network, and it can do anything else that comes to your mind. The only chance of understanding what such a function really does is to read it completely, and recursively do the same for every function it calls.

One of Smalltalk’s most unique and powerful features is also one of the least known outside the Smalltalk community. It’s a little method called become: .
What become: does is swap the identities of its receiver and its argument. That is, after
a become: b
all references to the object denoted by a before the call point refer to the object that was denoted by b, and vice versa.
Take a minute to internalize this; you might misunderstand it as something trivial. This is not about swapping two variables - it is literally about one object becoming another. I am not aware of any other language that has this feature. It is a feature of enormous power - and danger.
Consider the task of extending your language to support persistent objects. Say you want to load an object from disk, but don’t want to load all the objects it refers to transitively (otherwise, it’s just plain object deserialization). So you load the object itself, but instead of loading its direct references, you replace them with husk objects.
The husks stand in for the real data on secondary storage. That data is loaded lazily. When you actually need to invoke a method on a husk, its doesNotUnderstand: method loads the corresponding data object from disk (but again, not transitively).
Then, it does a become:, replacing all references to the husk with references to the newly loaded object, and retries the call.
Some persistence engines have done this sort of thing for decades - but they usually relied on low level access to the representation. Become: lets you do this at the source code level.
Now go do this in Java. Or even in another dynamic language. You will recognize that you can do a general form of futures this way, and hence laziness. All without privileged access to the workings of the implementation. It’s also useful for schema evolution - when you add an instance variable to a class, for example. You can “reshape” all the instances as needed.
Of course, you shouldn’t use become: casually. It comes at a cost, which may be prohibitive in many implementations. In early Smalltalks, become: was cheap, because all objects were referenced indirectly by means of an object table. In the absence of an object table, become: traverses the heap in a manner similar to a garbage collector. The more memory you have, the more expensive become: becomes.

We only have this idea of twoness, like a context space in which we can fill with names, meanings, like left and right, like sun and the moon, like two people, or maybe just a number two,
2. We could write any other number too, like
3. So into the Haskell interpreter, we write a number
Prelude λ> 2 2
And Haskell answers back with
2. So our conversation, our inquiry could be described as a process, a function, some relation from number 2 to a number 2,
2 -> 2. We use the arrow,
-> symbol so that we can realize the connectedness of this process, something from something into something, from a variable to some variable, from an
a to an
a. Like a question and then an answer it is more than just
2 and some number
2, not quite like
2 = 2, we can reason about
2 -> 2 like
input -> output, it's only equality being the fact that something returns what was already given. I am using the words giving and taking though the main ideas here is the idea of an identity. What could it answer to our simple inquiry? Haskell interpreter could have given us a number
3 but then we would not know if we are communicating at all. The meaning would not be referentially transparent. If I call you that means I would like to talk to you and not to someone else. I only need to save your number once, and then each time when I call you you will answer. So basically our relation is referentially transparent. We could also say that in our program if we define some variable or a function then this definition will not change, it cannot, it makes no sense to change. Otherwise we would not know any more who to trust, what is real and what is not.
I mean, if I just give you an apple without asking anything in return and you give me back a pear one time and next time you give me a lecture in mathematics what does that tell us about this exchange? It is impure, it is not clear what will I get, it is like talking to a madman, we never know what we will get.

use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
1,186 users here now
/r/programming is a reddit for discussion and news about computer programming
Please try to keep submissions on topic and of high quality.
Just because it has a computer in it doesn't make it programming.
Memes and image macros are not acceptable forms of content.
If there is no code in your link, it probably doesn't belong here.
App demos should include code and/or architecture discussion.
Please follow proper reddiquette.
Do you have a question? Check out /r/learnprogramming, /r/cscareerquestions, or stackoverflow.
Do you have something funny to share with fellow programmers? Please take it to /r/ProgrammerHumor/.
For posting job listings, please visit /r/forhire or /r/jobbit.
Check out our faq. It could use some updating.
If you're an all-star hacker (or even just beginning), why not join the discussion at /r/redditdev and steal our reddit code!
This is an archived post. You won't be able to vote or comment.
What is the advantage of currying? (programmers.stackexchange.com)
submitted 3 years ago by [deleted]
view the rest of the comments →
[–]tailcalled 3 points4 points5 points 3 years ago (7 children)
No I'm not. Take the Haskell function map:
map :: (a -> b) -> ([a] -> [b])
This function is curried. Its "first" parameter has the type (a -> b) while the second has [a]. Currying is the technique of making curried functions.
(a -> b)
Take the following piece of Scala code:
val div = (x: Int, y: Int) => x / y
val half = div(_: Int, 2)
In this case, to create half, we partially apply div with 2 as the second parameter.
[–]finprogger -3 points-2 points-1 points 3 years ago (6 children)
I don't see how what you just wrote contradicts what I said.

It's not a difficult concept -- I use it on the Unix command line all the time -- but there was no book that could teach a practical programmer like me why it's interesting.
Bryan: A benefit to me in writing this and also to my co-authors, John and Don, was that we had all been at various times immersed in lots and lots of work in all kinds of other languages. I've written a huge amount of code in C++, in Python, in Lisp, in Perl. John has a similarly diverse background. If you look for his name on Amazon, you'll find that he's written several Python books for example.
Don is probably the most academically inclined of us, but he works in languages like C and C++ every day as part of his job. We didn't come at this with any kind of an ivory tower background or perspective. We were all rooted in how do I do things that are interesting and useful rather than how do I express things that are algorithmically pure. We're certainly interested in that and find it to be a lot of fun, but I find being able to execute things and have them do stuff that's valuable to me to be as much a charge as any of the more esoteric pursuits.
Why should your average programmer care if something is algorithmically pure? What benefits are there to that?
Bryan: Why should an average programmer care? An average programmer is going to be concerned with a lot of different things simultaneously, right? If you're working on a large body of code, you're going to be concerned about modularity. Can I understand part of a program in isolation from the rest of it? Can I test part of a program in isolation from the rest of it? Can I read a particular part of a program and be able to make a fair estimate as to what it's really trying to do? Those kinds of concerns pop up all the time in day-to-day programming.
the idea of writing code that is very tight and that has very little intertwining with the concerns of code nearby is not unique to Haskell; it's just that Haskell happens to carry it a particularly long distance. Several different things there play into that. One is the idea that most code, by default, does not have any kinds of externally visible side-effects. Given the same inputs, it will always produce the same outputs.
Is this most code in Haskell or most code in any programming?

What if the design decisions in a particular language are focused on robustness and maintainability?
You can make any language look good by comparing it to C++. If being functional is the magic bullet, then why do stateful languages like Python, Perl, Ruby, Lua, Lisp, etc. always do just as well as Haskell in this sort of omparison?
Unlike the rest of your commenters (as far as I can tell), I *have* used Haskell for real-world problems, and can confirm that (for the problems I’ve used it for), it is significantly more productive than imperative languages like Java, C++ or Ada.
I don’t think it’s quite ready for the maistream, but it’s definitely got promise.
I’m very sceptical about LOC as a measure. However, here’s a very recent informal data point, which I’m mentioning partly because it’s notable for the relatively controlled nature of the comparison: Lucian Wischik at Microsoft recently had to rewrite a 6,000 line F# program in C# (C# was required for unrelated reasons). It became 30,000 lines (references to comments by Lucian below). Now, this comparison is with essentially the same .NET libraries (F# adds a few minor libraries), the same (talented) programmer, the same .NET runtime, the same performance profile, the same problem specification, and the C# code has the advantage of being a reimplementation.
“However, in order for a FP to, well, run, someone, somewhere, must pull a lever so that the wheels start turning according to the spec of the FP, and what ticks under the FP ultimately does have state.”
That’s not the point. The point is that an FP utilizes a framework that *safely* translates from an abstract language without a concept of state to a concrete language that is basically nothing but state.
Likewise, object oriented languages do not actually have objects — whether they are detected at compile time or run time, they ultimately map to swaths of memory and functions.
It’s all smoke and mirrors. But it’s the magic of the smoke and mirrors that enhance our productivity. By building the funnel from a “safe”, “imaginary” language to the “dangerous”, “unproductive” one, we eliminate the problems inherent at the lower level.
Functional programming is not usually adopted because so many real-world systems are almost entirely side-effects.