the blog for developers

Is this functional programming?

Recently I’ve read a blog post by Keith Dahlby. It was titled “Is Functional Abstraction Too Clever?”. The title sounded more rhetoric because clearly Keith was very satisfied with the code he presented.

But it got me thinking again. After some time with Lisp at university, some Haskell and some functional thinking in Ruby, I’m deep into Scala for some months. I’ve written some functional code before in Java, but I’m using much more with Scala now. Many examples are mostly thinking and syntactic sugar to me, not something I can put a finger on: this is functional.

Haskell examples clearly are more functional – how so? – and some blog authors give very nice functional solutions. Some blog posts by Raganwald and Debasish gave me great insights into functional composability. But many examples of people new to functional programming do not look functional to me.

Keith says about functional programming:

To me, this is the value proposition of functional programming. By expressing the algorithm in terms of common operations, we’re able to spend more time thinking about the problem than the details of the solution.

Let’s take a look at his code:

static int[] GetSlots(int slots, int max)
{
    return new Random().Values(1, max)
                       .Take(slots - 1)
                       .Append(0, max)
                       .OrderBy(i => i)
                       .Pairwise((x, y) => y - x)
                       .ToArray();
}

Looks more like a filter pipeline than functional programming. Especially compared for example to the things Apocalisp does with functional programming. Years ago I wrote a rendering pipeline, before the functional hype, and it was just a collection of Filter objects which filtered and transformed input into output. There were many users, and no-one thought of it as “functional”. Keith goes on:

A similar change in an imperative implementation would almost certainly have been more involved and prone to error.

The example is written in C# so it supports closures neatly, transformed to Java it might look like this (the generics are not totally correct, I’m spoiled by Scala):

static int[] getSlots(int slots, int max) {
  return new Random()
      .values(1,max)
      .take(slots - 1)
      .append(0, max)
      .orderBy(new Order[int]() { public int by(int i) { return i })
      .pairwise(new Folder[int]() { public int fold(int x, int y) { return y - x })
      .toArray();
}

More involved? More prone to error? Not so sure. Someone with an OO background would righteously say: Sure this is OO. Method chaining and objects.

As we all know, Java is not a functional programming language, but an object oriented one. There isn’t much difference here, some shorter code, some syntactic sugar for creating functions. The only difference between object oriented and functional being that OO is more noisy? Is OO as superset of FP? The line blurs even more with Functional Java. Is functional not only a way of thinking? Immutable, side effect free, composable code blocks?

Is this example functional? What is functional? Your view would be appreciated, especially if you’re one of the usual suspects.

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.

11 Tweets

Leave a reply.

Comments

Pipe lines are definitely one example of functional programming. There are few things that define functional programming:

1. Immutability. Data never changes, you just produce new data.

2. Functions as data. Functions can be passed around and manipulated just like any other type of data.

There, now you have Lisp. :-)

In traditional OO programming, each method called would change the data in-place. Not that this is a requirement of OOP, but it comes so naturally that it became the standard.

If you want a real “this is different” example, you need to be returning functions. Something like the jquery pipeline model is more like it, where all the core library operations return functions not values. That example just returns a scalar, so it is not composable any more…

No. This is poor man’s stack programming.

Lucky for him he needed just one-level deep stack in this example. While this chain looks elegant and concise the “extension methods” used to enable it look verbose and complex as hell.

In addition to what Daniel Sobral said, another defining characteristic of functional programming is that the code should not produce any side effects. That is why there is no state and data has to be immutable.

There is also no notion of time in functional programming. If a function produces a result with a given set of parameters, it should always produce the same result given the same parameters.

You’re getting closer.

There is no Object-Oriented programming. There’s only programming. Functional Programming is simply programming with pure functions.

Your “objects” want to be functions.

Spoon boy

Spoon boy: Do not try and bend the objects. That’s impossible. Instead… only try to realize the truth.
Neo: What truth?
Spoon boy: There is no OOP.
Neo: There is no OOP?
Spoon boy: Then you’ll see, that it is not the OOP that bends, it is only yourself.

I don’t think that’s functional programming – just an examlpe of a fluent interface http://www.martinfowler.com/bliki/FluentInterface.html

Your fluent interfaces want to be function composition. Let them.

Wedge

Sure it’s functional programming. Don’t get so caught up on the trendiness of functional programming to think that one way of using functional programming is less cool and less “truly, really functional” than another way. Using extension methods and other constructs to create a useful, readable, terse pipeline programming model is plenty “functional” even though it may not be quite as clever as a y-combinator or map reduce.

Remember that a Turing machine is the utter definition of the imperative, stateful programming model, yet every single function has its equivalent expression in Turing machine code form. They are two sides of the exact same coin. They are two levers under the same load, what matters is which lever is more useful to accomplish the task at hand.

Orthodoxy is for chumps, the important aspect is whether it’s GOOD programming, regardless of style.

Thanks for the comments everyone, glad to stir up a discussion. I think it’s important to realize that a “pipeline” just takes inputs from before the dot and returns new values out the “other side”. Assuming you’re not modifying shared state, that’s pretty much the definition of a function.

In this example, Values is always going to take the Random seed and return the sequence of values generated from it (technically this is modifying the state of the Random object, but in practice it doesn’t matter). Similarly, Pairwise is always going to return a new sequence generated from calling a function on adjacent elements in the input sequence. Whether or not they are “pure” seems irrelevant: they are useful abstractions implemented as functions – functional abstraction.

“While this chain looks elegant and concise the ‘extension methods’ used to enable it look verbose and complex as hell.”

Isn’t that the point of any abstraction, be it object-oriented or functional? Implementing the complex details once allows us to reuse them forever in “elegant and concise” compositions that greatly reduce the complexity of the code you’re actually interested in.

Cheers ~
Keith

For comparison with a purely functional language, here’s that code in Haskell:

getSlots n m = (zipWith (-) tail)
. sort
. ([0, m] ++)
. take (n - 1)
. randomRs (1, m - 1)

This is a pure function that takes a random number generator and returns an IO action within which the “slots” are provided.

Hmm… there are supposed to be some angle brackets in that Haskell code, but your comments system eated them.

I’m sorry, wordpress isn’t very good with code in comments. [Generics] worked for Scala though.

Florian Krüsch

sounds like you’re saying that programming a filter pipeline contradicts or is not real functional programming…
in fact functional programming is great for ensuring the correctness of the chaining, especially when using monads | http://en.wikipedia.org/wiki/Monad_(functional_programming)

Leave a Reply

What people wrote somewhere else:

Published new blog post: “Is this functional programming?” http://bit.ly/2B3jcR #FP #OO

This comment was originally posted on Twitter

Is this functional programming? http://bit.ly/3aYGhY

This comment was originally posted on Twitter

RT @codemonkeyism: Published new blog post: “Is this functional programming?” http://bit.ly/2B3jcR #FP #OO

This comment was originally posted on Twitter

“Is OO as superset of FP?”
http://bit.ly/3aYGhY

This comment was originally posted on Twitter

Is this functional programming? – http://bit.ly/3mPOSg

This comment was originally posted on Twitter

Code Monkeyism: Is this functional programming? http://bit.ly/1Ltbka via http://www.diigo.com

This comment was originally posted on Twitter

Is this functional programming? by @codemonkeyism http://ff.im/-adIjR

This comment was originally posted on Twitter

Is this functional programming – by @codemonkeyism http://bit.ly/4687vQ

This comment was originally posted on Twitter

RT @markhneedham: Is this functional programming – by @codemonkeyism http://bit.ly/4687vQ

This comment was originally posted on Twitter

Is this functional programming? http://bit.ly/rZsQK

This comment was originally posted on Twitter

@psnively So you’ve read this @codemonkeyism post: http://is.gd/4xB84 always hated that setters don’t return the object.

This comment was originally posted on Twitter

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?