r/programming • • May 15 '18

Demystifying functional programming (in a real company)

https://medium.com/building-nubank/demystifying-functional-programming-in-a-real-company-e954a2591504
127 Upvotes

51 comments sorted by

4

u/matthieum May 16 '18

But here’s where the magic happens: you’re not actually changing our-immutable-map; you're creating a new one that shares structure with our-immutable-map, but has a different value to :foo. Because it's so easy to share structure on this immutable world, everything is still quite efficient, memory-wise.

What's the performance cycles-wise?

As far as I know, the biggest issue with persistent data-structures is that representing arrays efficiently is an exercise left to the reader. There are multiple possibilities (finger-trees?), however I've never found one with performance anywhere close to a plain dumb array.

And this is a big issue, because the most efficient data-structures are built on top of arrays, as arrays play so nicely with CPU caches.

3

u/yogthos May 16 '18 edited May 16 '18

You can see the matrix of performance guarantees for Clojure data structures here, bottom line is that you end up with O(log32n) complexity for most cases. The important thing to keep in mind is that immutability is just the default. Clojure provides transients as a way to opt into mutability locally in cases where you need the additional performance. Ultimately, you can even drop down to plain old Java if you really wanted to.

The key part here is that Clojure makes it natural to write code without shared mutable state, and it takes a lot less discipline on the part of the user to structure applications in a way where you can safely do local reasoning.

1

u/matthieum May 16 '18

Thanks for the links.

The transients notion seems great.

The near-constant however is completely unclear. The performance of a data-structure is often a matter of the number of cache lines that one needs access to (as soon as the working set exceeds the cache size); and it is unclear to me how O(log32 n)1 performs here.

I expect, perhaps naively, that log32 n is proportional to the number of pointer dereference to access the element when indexing, and therefore the maximum number of page faults... though with a tree structure one can expect at least the root node (array?) to be warm in the cache since it's read on every access. However it's still pretty unclear what the memory layout is here. If naively based on the JVM, I'd expect 1 node to hold 1 array thereby requiring 2 or 3 memory allocations per level...

What's your experience with the performance of vector compared to a traditional Java array? What's the performance hit of "near-constant"?

1 It's not clear either why the use of log32, instead of log2. From a big O perspective, both are just a constant apart, so log32 is logarithmic... My supposition is that arrays of 32 elements are used in some kind of B-Tree arrangements, and thus log32 is used to hint at the branching factor...

1

u/yogthos May 16 '18

You can see a benchmark for Clojure vector here, note that's a few years old and there have been some improvements in the implementation since.

In practical terms, I've had very few situations where I needed to use transients over the years. My team has been developing Clojure applications for around 8 years now, and we haven't found any performance problems compared to similar types of applications we've developed with Java previously while writing idiomatic Clojure.

1

u/matthieum May 18 '18

That's great to hear!

I guess I am just a tad too obsessed for performance, coming at it from the angle of HFT systems.

1

u/yogthos May 18 '18

It's always a case of using the right tool for the job, this talk might be of interest if you're working with HFT.

13

u/[deleted] May 15 '18

I love reading about functional programming

9

u/yogthos May 16 '18

What I liked about the article is that it show how a few fairly simple concepts can translate into tangible benefits in real world projects. A lot of people seem to have the idea that FP is complex, but it really doesn't need to be.

3

u/[deleted] May 16 '18

I agree, FP can be simple if explained in a concise way. The writer has done a good job here!

73

u/Milyardo May 15 '18

What do functional programmers do in fake companies?

108

u/BrokenHS May 15 '18

Write blogs.

48

u/[deleted] May 15 '18

About monads.

22

u/ggtsu_00 May 16 '18

And curry.

7

u/cbleslie May 16 '18

...and other spicy gravys.

2

u/Sinidir May 16 '18

While eating burritos.

3

u/[deleted] May 16 '18

Can confirm. Eating a curry burrito while posting.

22

u/the_gnarts May 15 '18

What do functional programmers do in fake companies?

Non-functional programming, obviously.

11

u/BCosbyDidNothinWrong May 16 '18

Haskell one liners.

8

u/[deleted] May 16 '18

They solve fake business problems by not mutating state.

36

u/arbitrarycivilian May 16 '18

I think it's great to point out that you don't need to have a PhD in category theory to take advantage of functional programming. Monads are certainly overblown.

But one feature which I find equally indispensable in functional programming, and which Clojure lacks, is algebraic data types. To me FP without ADTs is like OOP without interfaces.

15

u/makeshift_mike May 16 '18

You don’t even need to be using a functional language to take advantage of FP. There’s a great article called Functional Programming in C++ where John Carmack talks about general FP principles like immutability and minimizing shared state, applied to a language that’s pretty far from functional.

6

u/[deleted] May 16 '18

Agreed about ADTs - once you go ADTs, you can't....umm...something.

2

u/the_whalerus May 16 '18

Isnt that intentional? I seem to recall something from Rich Hickey where he was bashing ADTs

9

u/max_maxima May 16 '18

He was bashing ADTs... by mistakenly bashing pattern matching.

4

u/[deleted] May 16 '18

And bashing pattern matching itself seems like a really misguided position

1

u/lilactown May 16 '18

You don't really need ADTs in Clojure that often. Since it's dynamically typed, and most data is passed around as collections of primitives, pretty much all of your typical functions can operate on the same stuff.

When you really need to tie behavior to a type or an interface, protocols have given more than any other language I've used in terms of polymorphism and ability to extend types, interfaces, etc.

-2

u/[deleted] May 16 '18

To me FP without ADTs is like OOP without interfaces.

Oh, like Smalltalk? Or Python? Or C++?

Lots of OO languages don't have interfaces. Interfaces were put into Java because its designers wanted to avoid the tricky semantics associated with multiple inheritance.

See also: traits in Scala.

15

u/aejt May 16 '18

A class with only pure virtual functions in C++ is more or less an interface.

13

u/chucker23n May 16 '18

Oh, like Smalltalk?

Doesn't Smalltalk have protocols, like Objective-C? If so, it has interfaces by a different name.

7

u/doom_Oo7 May 16 '18

interface here is meant as a concept.

the following C struct :

struct foo { 
  int x;
  float bar;
};

conforms to a bunch of interfaces, even if the language does not allow to express them as first-class objects.

3

u/jerf May 16 '18

In addition to aejt's point, Python and Smalltalk have dynamic language interfaces, which are undeclared, but exist. It's why they talk about "duck typing" so much in the Python world, for instance. All dynamically-typed languages have interfaces.

53

u/doomchild May 16 '18

We snuck functional programming in by the backdoor. We wrote a useful little extras library in Java that had Maybe, Either, and Validation, and got everybody to use it, then told them they'd been using FP without knowing it.

3

u/GuyWithLag May 16 '18

We did that via rxjava.

2

u/langlo94 May 16 '18

At which point you sacrificed them on the altar of Stallman?

0

u/[deleted] May 16 '18

[deleted]

4

u/langlo94 May 16 '18

And that's why he's worshipped.

1

u/BeneficialContext May 16 '18

That makes no sense. A real coder takes whatever is useful from other paradigms.

0

u/[deleted] May 16 '18

[deleted]

5

u/[deleted] May 16 '18

Except the Left should be a Semigroup, and the Validation should form a Monoid iff the Right does.

In English: a Validation should be Either "success" (Right), possibly including "empty," like a database query that successfully returns no results, or a non-empty "failure" (Left), hence a Semigroup, which is a binary associative operator without "empty." It would be meaningless to have an "empty failure." The "empty" for the Monoid instance for Validation is a Validation constructed from the "empty" for the Right type of the Validation. The binary associative operation for Validation can be either "failure results in failure" or "success results in success." Scalaz has a Monoid instance for Validation whose binary associative operator is +++, which is failure-accumulating, which probably comports with most people's expectations. But you could certainly provide a Monoid using +|+, which is success-accumulating, instead.

14

u/doomchild May 16 '18

I stab people who talk like that. It's a freaking box that aggregates error cases or passes through a successful value. Mathy talk makes me angry.

14

u/[deleted] May 16 '18

so it's not just me?

i remember the first time i went to look up the term 'dependency injection' only to be greeted with articles laid out as a fractal of jargon.

why didn't you say 'we're just going to pass shit in through a parameter'?

4

u/doomchild May 16 '18

It's definitely not just you.

2

u/liuwenhao May 16 '18

IoC CONTAINERZ !!!

1

u/Milyardo May 17 '18

People who are partial to math jargon inclined didn't come up with dependency injection. It's the design everything by committee crowd who came up with that. Computer scientist find dependency injection just as pretentious.

5

u/DonnyTheWalrus May 16 '18

It's fine when you're talking about the literal math side of programming -- type theory, etc., which many users of FP are involved with. One of the main attributes of pure FP is correctness, alongside expressiveness in the type system, both of which are derived from the formal mathematical definitions of the language and its evaluation. But I agree that reliance on this sort of jargon when talking about practical applications is off-putting.

The problem as I see it is there's often no clear delineation between places that talk about the math dimension of FP and those who talk about the practical side of it. A lot of writers on FP topics seem to assume that most FP users are similar in background to themselves. Furthermore, when you do have the background to understand what a monad is, or a monoid, or etc., there's no more efficient way to communicate exactly what you're intending than by using those well-defined terms.

For anyone who's curious about FP but is also put off by this sort of jargon, I've found F# for Fun and Profit to be a good resource; Scott Wlaschin stays away from jargon for jargon's sake and is very focused on the practical. For instance, he has a pretty well known post on what he terms railway-oriented programming, which is essentially about monads, bind, and so on but explained very clearly. It's obviously focused on F#, but F# is basically OCaml/.NET with some extras, so most of it is fairly generally applicable.

1

u/doomchild May 16 '18

I think that's my biggest source of frustration. Not all of us got through all the math required by our college.

4

u/[deleted] May 16 '18

To make this more understandable: you want to either have a data structure where everything is valid (as in: where the value is wrapped in an Ok/Right) or a validation result which has the combined amount of errors (wrapped in an Err/Left, combined/reduced using a function from the "Monoid" interface which just appends all validation errors in a list).

14

u/JoseJimeniz May 16 '18

I love this video which explains F# functional programming for C# developers. It's one of the best introductions to anything ever:

The reason is so amazing is because he takes C# code and he transforms it into functional F# code - piece by piece before your very eyes.

And he does it in a way that makes functional-programming obvious and intuitive.

Functional programming is no longer this massive abstract blob of monads and other silly words.

  • it's programming using functions

And so you begin to understand that functional programming researchers take this idea, and try to formalize it, with esoteric terms, and strange concepts, and see how far they could go down the rabbit hole.

But in the end it's still just programming with functions.

And once you realize that, you can start to use it in every language.

You really should give it a watch.

-32

u/[deleted] May 16 '18

Had to stop reading once that asinine example of foo/baz was laid out.

40

u/OverflowingSarcasm May 16 '18

I wish you "had to stop" writing your comment, too.

-29

u/[deleted] May 16 '18

You’re trying too hard Mr Sarcasm

1

u/jeremy1015 May 16 '18

Oh my god you are so right. Why would the author start with a simple example using variable names common to every blog post about programming ever?

It’s almost like he wanted users new to these concepts to understand them.

2

u/[deleted] May 16 '18

Lol you see nothing wrong with the specifics of their example?