53 points · by subbz · 12y ago · 98 comments
Functional programming is great and feels right, I am amazed how knowledge of fp affects my js, C# and Python up to this day. But from a social perspective: Loose the smugness, and then we'll talk fp.
It takes me a few seconds to rewrite foldl from rote understanding: foldl f z (x:xs) = foldl f (f x) xs, because it takes a function, a 'zero', a list of head and tail, and calls itself again with the same function, a zero 'going up' (so accumulating) and a list 'going down' (being exhausted). So as you see this is an almost a visual way to understand it, which is natural to those that already are familiar with these abstractions, but is meaningless to those who don't.
If someone then says "how dare you ask that" then they have the wrong approach to things. Socrates asked every question and thought they were all valid. By asking the basics you learn the abstraction as if you're proving it to yourself, and that's more powerful.
So it boils down to familiarity, is what I'm trying to say. I usually come across as more passionate than arrogant about it. If you stick to it, it will make sense. It took me 4 years of Haskell exploration for it all to click really hard and now I'm trying to shorten other people's paths. In my opinion the gap is around mathematical abstractions, how they're created, what do they mean, how they actually relate to reality, and what work do they accomplish for us that we then don't need to do anymore.
I think this type of explanation falls into what the parent post is talking about. That is a technical accurate but very dry way to describe a construct that simply calls the function it's given for every element in a collection and returns the accumulation of the results. Granted you can dive into all sorts of discussions about what that _really_ means and what power it gives you, but save that for much later, it isn't introductory material.
An analogy to how functional programming often is taught would be if I tried to teach a new programming language by going over the BNF grammar first without context instead of starting with how the language is actually used in practice. It may be more 'technically correct' but it's a terribly ineffective way to learn for most people, even those who know and understand BNF. People are often more interested in what they can do or create with this new thing, not the nitty gritty details of how it works mathematically even if they intend to get into the details later.
Having said that, for an example of how I would actually explain some FP to someone, search this page for "DomainList" and I have an explanation there.
I agree with you 100%; my belief is that mathematics and its notation often gets introduced too early, before students have had a chance to build intuition.
I'm not saying that actual smugness doesn't exist, but almost all the time it's actually just projection from someone who's used to being in the know now struggling to understand something new.
Remember when you explained to someone using a language lower on the power spectrum (VB or PHP maybe) why they should use all the cool stuff that you can do in Ruby or Python, how much more productive they would be, how much more fun it was to work in? You thought you were helping them and showing your excitement, you wish someone had told you this a long time ago!
Unless you are a world class educator they were confused by some parts, threatened that their investment in their current language was losing value and worried they might not be able to function in this new world and therefore protected their ego by seeing you as smug.
Second: The blub paradox (at least as posed by Paul Graham) is wrong. To see why, just look at Lisp and Haskell. Users of both languages are sure that they're at the top of the power curve. They're sure that when they look at the other language, they're looking down, and they can tell you precisely why ("it doesn't even have macros" and "it doesn't even have a decent type system", respectively). But they can't both be looking down at each other - unless languages cannot actually all be ordered along a single axis called "power".
In fact, you have to ask "power for what"? Once you do, you might start to see language power more as a tree than as a single line. You can really only compare power between languages on the same branch. Pick the language that gets you the furthest in the direction that your problem lies.
Those two abstractions are several times more powerful than the overly constrained abstractions imposed by OOP. The power of lisp is that it is homoiconic, and it asks what it means to write programs that write programs. The power of Haskell is that it is algebraic, and it asks what it means to execute a mathematical proof.
Both therefore have the power to really abstract away from things in any way you want. They do not constrain the programmer with an abstraction that is too high and not composable, as are (mathematical) functions and macros (which are composable with hygiene). The prevailing paradigm offers poor substitutes for composability and can simulate very poorly abstractions that are lower than Objects (thereby needing design patterns to make up for starting so high in the abstraction tower).
That's my point. It absolutely doesn't seem that way to me, because I know Haskell and Lisp.
I'm also personal friends with PHP developers who I used to work with and they have exactly the same attitude towards anyone talking about Ruby or Python or literally anything else.
They are angry at the bullshit that these smug language jerks keep throwing their way about how "bad" their perfectly good language is.
Programming in PHP must have a similar effect.
Then, there are other FP languages, which you can easily learn in a few days/weeks, very nice and natural, e.g. OCaml, or SML, or maybe Scheme(Clojure?).
It's too mainstream for me now, I'll have to switch to reactive programming.
[1] https://github.com/CrossEye/ramda
More info on the topic:
The book is also very good: https://leanpub.com/javascript-allonge
- Don't understand it - Are afraid of it - Find it too complicated
Personally, since I work in storage which is where we have to store all the "state" that the FP folks have defined into Somebody Else's Problem, I have little tolerance for that particular flavor of the month.
You say this as if functional programmers somehow make your life harder... It's not like they're decrying the existence of persistent storage or trying to put you out of business :)
Also, functional programming isn't about offloading state, it's about removing it from programs altogether (in the sense of "state" being something that isn't explicitly passed through function arguments).
Still, even if you store your internal state, that's hardly what functional programming means when opposing state.
In reality, someone can take advantage of FP with absolutely no understanding of the mathematical underpinnings. I think that's what the author was trying to get across.
Just because I speak French and English fluently does not mean I can speak Japanese. My wife is Japanese, and speaks it fluently. We've been together 19 years. I've tried to learn. it just does not make sense. It would be nice, because I have relatives there, and I could go live there, legally, but it just doesn't make sense in my brain.
What can I do?
Functional programming is the same. Every couple of years I take a look, and I recoil in confusion.
It also doesn't help that people make fun of me for seeming dumb.
Then I had a class where we learned Haskell with one of the best professors in the department. He basically taught me all of the great things about functional programming and now I try to use concepts from that class in whatever language I'm programming in.
Learning functional programming is paradigm-shifting and gives you a much broader set of tools to work with, but if it's not taught well it won't help you.
The fun part is that many languages end up aiming for it. Good multithreaded/reentrant code is almost functional. I just saw a ruby rant asking to avoid mutation as much as possible. Same goes for PHP PSR-x ...
Functional programming suffers from acute mathematitis, the people behind it are fond of iterating too fast around their newfound concepts and it end up as cryptic as possible.
I want to write a program that reads one text file, and outputs another.
Let's say the first file contains a list of emails, one email per line.
The second file should contain the list of email domains in the first file, one line per email domain.
Procedurally, I would simply declare a list, read the file of emails, line by line, split each one on the @ symbol, and if the part on the right was not already on the list, I would add it to the list.
At the end, I would write the list to a new file, one line per item in the list.
How would one do that using functional programming?
We define what we have first (after all this is mathematics):
EmailList = a list of Email
Email = a string that goes "something" then "@" then "domain"
Now what we want:
DomainList, no duplicates.
Ok so no we're set up. We want a function that takes us from an EmailList to DomainList, as defined above. There are no objects so we simply say the relationships between things. I will introduce the tools we need:
map = takes a function and a list and applies that function to every element of the list, returning a new list.
We use map over EmailList with the function extractDomain which we will write later (it's trivial to do without mutation so I won't show here).
So now we have a list of domains, but there might be duplicates.
So now I have DomainList(with duplicates) and I want DomainList(without duplicates), so I want a function from DomainList to DomainList.
Well, what's the difference between what I have and what I want? What I have has too much, and I want less (ie. the list I have has too many domains (duplicates) and I want fewer (unique)).
filter = takes a list and a function. That function it takes, that you will supply to filter, we'll call f. Function f takes one list element (so filter will call f for every element) and it must return a boolean to mean whether that element should go into the new list, or if it should not go into the list.
So we could use filter to go from a DomainList with too much, to a DomainList with fewer things. However each time our function f is called, we don't know if this function has already been called before with that same domain; and because we don't have state to change a variable to keep a tally, it seems impossible.
So let's approach the problem in a different way. One thing we could do is sort the list, then group adjacent similar items, then map over the list taking the first element of each item. But we won't do that.
We need something more generic than filter. Let's look at fold.
fold = takes a list, a function f, and a starting point z (that we call 'zero'). For each element of the list, it calls your supplied function f with the current element and the zero; but then, it would be useless because it would be the same zero all the time. So what fold does, to be useful, is that whatever the result of calling your function f with a list item and the zero is, THAT value (so the value the call to yourFunctionF(list_item, zero) returns) will be the next 'zero'. So now we have a little machine called fold that can thread something we have through its inner mechanism and play along with us.
Using that we can say the zero is the list of elements we've seen so far.
So now our DomainList -> DomainList function will be a fold. That fold will take a the DomainList we have, and a zero that will be the empty list (to start with!) and a function f. That function f will simply check if the item is inside zero. If it is, then simply return zero (because that will be the zero for the next call to f!); if it's not, then return a new zero with that item added to it.
Now we've achieved the goal without any mutation (ie. without us talking/concerning ourselves with any mutation. of course there's lots of mutation going on in RAM but the point is not to eliminate that!)
Does that help?
(ns my.namespace
(:require [clojure.string :as str]))
(->> (str/split (slurp "/home/deadghost/fake-emails") #"\n")
(map #(second (str/split % #"@")))
set
(str/join "\n")
(spit "/home/deadghost/new-file"))
Read entire file, split by newlines into a vector, split each element by @ and take the second part of each split, convert to set to remove duplicates, join set elements with newline and spit to new file.Clear as mud?
OOP just feel more eloquent to look at personally.
Struct.function(arg1, arg2, arg3);
feels more atheistically pleasing to my mental model of programming then function(struct, arg1, arg2, arg3);
This means more complex function definitions. While I can define multiple .close(); functions, that only operate in relation to their connection type I.E.: tcpConnection, serialConnection can each call their own close(). In FP I have to actually state either: fn close<T>(&:<T>){
if(<T>::isType(tcpConnection)){
tcpConnectionClose(<T>);
}else if(<T>::isType(serialConnection)){
serialConnectionClose(<T>);
}else{
//throw exception
}
}
Or I just make primitive calls to each connection type tcpConnectionClose(*);
This just doesn't stroke me the right way. It feels like bulky, over necessary coding when you take into account objects exist. I'm interested in FP, I feel it has to offer something for people to jump on it, but I just don't get it.> letting the compiler figure out which one to call when and obviating the runtime exception entirely.
That is how FP eliminates a whole category of bugs. You have to have "experience", which some love to boast, to know that it's better to have an else clause there and throw an exception.
If you think that's basic knowledge you'd be surprised with how little do "experienced" programmers that get paid very handsomely actually know; I've met 30-year of experience programmers that do not believe that the final-else-then-exception pattern is a good idea, because they think "crashing the program is never good". So what ends up happening is of course the program ends up crashing anyway (supposing you have passed an invalid connection in that case) but now the stack trace is potentially much deeper than it needs to be, and therefore misleading. All stack traces lose their value collectively because now we can't tell the good ones from the bad. That can make debugging harder than it needs to be.
But instead in FP, because it's a fundamentally different way to program, that situation doesn't even arise in the first place, obviating a solution. In FP things are modeled differently from OO, it's not just "procedures without an object jacket". The advantage here is the compiler verifies the "object" selection for you (which "class"/type of connection) and can provide some mathematical guarantees. Those guarantees are what metonymically "eliminate bugs".
So we can rely less on the programmer and more on the compiler. You know, like it's meant to be. After all we are sitting in front of a computer, so we should just let it do its thing without telling it how. Turns out autonomy in coming up with a solution is good both for the programmer and for the computer (and then again for the programmer).
http://clojure.org/multimethods
I encountered this recently but I'll try to give a (bad) explanation.
You'll call `function(thing, arg1, arg2, arg3);`. Another function will run on the arguments and return a dispatch value. For example, it will check what `thing` is and return `struct`. The `struct` version of that function is then run on the args and gives you your value.
In this way you can define several `close` functions based on dispatch value instead of one monolith nested if/else `close`.
I'm on the opposite side of the fence, OOP has never ever appealed to me. "Why would anyone want to use this crazy mess?" kind of thing. I'm sure I can learn to appreciate it with time but it's not a native paradigm to my mind.
I only have experience with lisps when it comes to functional programming but the reason I enjoy it is that it's simple. You have functions and you have data. Functions transform data to more data and the two aren't tightly bound. If you pass a function a value it will always return the same result if you pass it the same value.
THE clojure video: http://www.infoq.com/presentations/Simple-Made-Easy (I don't think he even says the word clojure in the entire hour presentation.)
FP has nothing to do with procedural programming at all, it is fundamentally different and diametrically opposed to both procedural and object oriented programming, which are then both in the same group away from FP.
You should look up some tutorials on FP if you want to understand what it means in practice.
Well, that's not helping. But I agree that devs should learn FP, and I now write in a much more functional style than I used to. I resisted for a long time, and that was a mistake.
I personally find this view a little overbearing.
In "lay programmer's" terms, functions as first-class objects can often come down to being able to pass functions to other functions or function composition. Most of us learned about function composition in Algebra 2... So that's pretty straightforward even at its worst.
Eliminating side effects is equally straightforward in that all it means is that any variables outside the scope of a given function are not changed by the function.
def a(b):
m = 0
return b(m)
Or even: def a(b):
m = b(1)
return m+7
I don't see how these are not a form of function composition. I'm definitely no expert. But I'd really appreciate an elaboration so I can learn from any mistake I'm making. compose : (a -> b) -> (b -> c) -> (a -> c)
a `compose` b = \x -> b(a(x))
However, there is a whole spectrum of additionally possible functions which can be built to accept functions as arguments. Here's a couple of example: partial3 : (Integer -> Integer -> Integer) -> (Integer -> Integer)
partial3 f = f 3
map : [a] -> (a -> b) -> [b]
map [] f = []
map (x:xs) f = (f x):(map xs f)
The first one takes a function and applies an argument, 3; the next one takes a list and a function and maps the list using the provided function. The idea of functions as arguments is a very powerful one, and from my understanding one with which people sometimes struggle. compose :: (b -> c) -> (a -> b) -> a -> c
compose f g x = f (g x)
I'm not sure about the math curriculum in USA but in linear algebra you have functions that operate on functions.