114 points · by codecurve · 11y ago · 64 comments
E.g. when most of the code I write is database queries, performing business logic, calls to memcached, handling error cases/messages, validating input, and then outputting data in various formats (JSON, HTML templates, etc.) -- how/where does FP help with that?
Is FP more a paradigm for computationally intensive programming? Back-end web programming? Front-end? I come across "FP is good" all the time, but I've never found any kind of resource to help me understand the tradeoffs between FP and non-FP, where it makes sense to use it and where it doesn't. Or any kind of FP tutorial on how to build, for example, a basic web CRUD app.
It has nothing to do at all with what kind of thing you are building, it is a general means of expressing common patterns in programs. Much of the reason people like FP is because it provides a high degree of code reuse in standardized forms, and it does so with a good bit of terseness and flexibility. Just about everything else in the FP world is about optimizing safety, performance, and reliability without giving up these benefits.
When someone says "FP is good," it's analogous to saying "well-commented code is good." As in, it's good everywhere you have the time to do it correctly. (There just happens to be a lot of debate about how to do it correctly.)
Sure, I get what it is but what I don't get is how I would use it in my world of mutating data and side-effects.
I understand what you mean, because even though I love FP a lot, I still struggle to conceive whole systems (other than simple map-filter dataflow ones) this way. So far I keep the FP principles for small pieces, hoping later on I'll find a way to close the gaps.
[1] John Backus tried to design purely functional languages a long time ago and he hit the IO wall (he mentions it in some article). Haskellers had issues at first and found that Monads were a nice functional way to express IO-like logic. It's still something weird, a lot less clean than purely functional expressions to be evaluated.
It is, again, like saying "I don't see how this helps me in my world of uncommented code". You could just comment your code, right?
(Or if that's too much work, or it's a shared code base and you can't get buy-in, just start going forward?)
It's refreshing getting rid of the whole class of bugs caused by developers using harmless sounding method names that subtly alter their data.
It did require substantial rewriting of the basic units of the program I tried it in, so there is that...
Calculus is not for economics but there are guides to calculus for economics majors. A given language isn't word processing but a "guide to writing a word process in Pascal" is not unimaginable.
The parent asked for a guide to using functional programming for the web back end. I'm not sure why sure a thing couldn't exist.
In the case of JS, using functional techniques simplifies the code quite substantially. Testing becomes easier. Immutable data can be much easier to reason about. It's often orthogonal to OOP, functional techniques in the small, OOP to structure in the large. FRP is very useful for interactions front-end (form validation for example), but also is just all-round terrific for message passing. Recursion is ideal for certain scenarios. If you take something like handling errors, an example would be the way promises deal with them, with the ability to collect at the end of the chain, or deal on a case-by-case basis.
I'm just listing stuff off the top of my head; with a general-purpose language [with the option of different paradigms] it's not so much a case of 'build a web app', it's more 'if you use these techniques, you may well find that your code is easier to reason about'.
I think the metaphor I like is that with FP it's as if you have an assembly line of functions, and you pass your data down the line, with each function transforming in turn; each function can easily be ripped out and/or replaced and tested. There are multiple downsides and pitfalls - overly abstracted code being a very common one, but as a general approach it's often extremely useful.
Books maybe worth a flick through (tried to pick stuff that is less...abstract, & I have specific interests, so am biased) - Functional JS by Michael Fogus, Programming Elixir by Dave Thomas, Learn You Some Erlang for Great Good by Fred Hébert & Programming Erlang by Joe Armstrong
Railway Oriented Programming (F#) http://fsharpforfunandprofit.com/rop/
Netflix talking about FRP http://youtu.be/XRYN2xt11Ek
(sorry for the slightly rambling post, typing & copy/pasting ain't great on a phone)
I personally like Eric Normand's "Web Development in Clojure" videos[0].
Like another commenter mentioned, FP is not a tool to use here but not there, it's a general method of abstraction that can reduce a lot of clutter and boilerplate, and make the code more terse, so that when you read it, you see what your are doing, rather than be entangled in all the details of how you are doing it.
I personally utilize functional programming concepts all the time, to the point that I get very frustrated when I have to work in a language that doesn't support functional programming.
We then ended up mixing in some WebGL for high performance parts, and that turned out to work best as more object-oriented code. Probably partly due to the library we used.
http://realworldhaskell.org/ (sometimes code is too old to compile)
also good: https://nikita-volkov.github.io/a-taste-of-state-parsers-are...
> database queries
https://www.fpcomplete.com/school/advanced-haskell/persisten...
> performing business logic
Give a more specific example. Preferably with code, and I'll respond with a Haskell/FP equivalent.
> calls to memcached,
import qualified Database.Memcache.Client as M
mc <- M.newClient [M.ServerSpec "localhost" 11211 M.NoAuth] M.defaultOptions
M.set mc "key" "value" 0 0
v <- M.get mc "key"
More on memcache here: http://hackage.haskell.org/package/memcache> handling error cases/messages,
http://book.realworldhaskell.org/read/error-handling.html
> validating input
Give an example on input. Depending on complexity I'd most likely use attoparsec or maybe just stuff from the text library.
> outputting data in various formats (JSON, HTML templates, etc.)
JSON: http://hackage.haskell.org/package/aeson
HTML: Not sure about outputting html from a data type's structure, but this might be what you are looking for: http://hackage.haskell.org/package/blaze-html
> how/where does FP help with that?
First I need to know what your definition of FP is. I think it's safe for me to say without knowing your definition that it doesn't help with those specifically as much as it does with tying them all together and having a greater handle on what their behavior/interaction with eachother will be.
> Is FP more a paradigm for computationally intensive programming? Back-end web programming? Front-end?
General purpose.
> I come across "FP is good" all the time, but I've never found any kind of resource to help me understand the tradeoffs between FP and non-FP, where it makes sense to use it and where it doesn't.
That's a shame and I couldn't find really good ones either. To be fair though, such a comparison wouldn't be the easiest to create. I'll add it to my "attempt to blog about" list and we'll see what happens.
In the meantime this might help:
http://phaazon.blogspot.com/2014/02/regular-imperative-state...
> Or any kind of FP tutorial on how to build, for example, a basic web CRUD app.
https://www.fpcomplete.com/school/advanced-haskell/building-...
http://adit.io/posts/2013-04-15-making-a-website-with-haskel...
https://github.com/ryantrinkle/memoise
https://news.ycombinator.com/item?id=9830431
I'm also in the middle of creating a Haskell version of the Django polls tutorial:
(And to all the other replies/links as well, I can't edit my original comment anymore and don't want to take up space with extra comments. But all very appreciated!)
I also have a few semi-useful things on my blog currently so I'll go ahead and put that in my profile as well.
EDIT: Additionally, if you experiment with Haskell be sure to use Stack[0] instead of cabal to avoid potential headaches. The Stack wiki[1] was a useful but easily overlooked resource for me as well.
High-order function in java don't exist, so one would do :
new Thread(new Runnable() { ... }).start();
A builder pattern can be distilled down as a form of partial application (or, currying, if you like. They aren't the same thing, but are very similar): alertDialog
.setMessage(...)
.setPositiveButtonText(...)
.setNegativeButtonText(...)
.setPositiveButtonOnClickListener(...)
.setNegativeButtonOnClickListener(...)
.build()
.show()
Functors (in OCaml) can be viewed as Java's abstract-generic-classes with dependency injection [0]. Note that functors in different languages mean different things.Monads are tricky to understand [1], I have been led to believe. But if you use the promises API in javascript, then you're using a form of monad [2].
If you're familiar with javascript, have a look at: https://www.youtube.com/watch?v=m3svKOdZijA (Hey Underscore, you're doing it wrong!) I think the best way is to read a book on fn-programming. I've heard most people recommend these (pick a language, and choose a book; you cannot go wrong with any of these):
Functional DS: http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf
Real World Haskell: http://book.realworldhaskell.org/read/
Real World OCaml: https://realworldocaml.org/v1/en/html/index.html The Joy of Clojure: http://www.manning.com/fogus2/
Learn You a Haskell for Greater Good: http://learnyouahaskell.com/chapters
Learn You some Erlang for Greater Good: http://learnyousomeerlang.com/content
Systems Programming in OCaml: https://ocaml.github.io/ocamlunix/
[0] https://monadmadness.wordpress.com/2015/01/02/monoids-functo...
Rather than a "class" with one "do it" method, which also has a constructor to initialize configurations (or worse, a bunch of "setters"), just make the configuration (or other "dependency") values the leading parameters of a function. Then, partially evaluating the function to supply those values does the same thing that "dependency injection" does, only without the logorrhea of a class.
Programmers are good at abstract patterns though! Look at iterators: they're obscure and complex if you've never encountered them, but now they seem really easy. The same is true with monads.
A monad is an abstraction pattern that, as applied in typed functional programming, has three parts.
1. A type constructor that takes a type and returns an type. Enough languages have an Optional construct now that this should be sensible to anyone paying attention.. If Integer and Optional<Integer> are types that have values, Optional is a type constructor.
2. A function for injecting a value in an appropriate manner. To stick with java-ish syntax, it'd look like Optional<T> inject(T x) { ... }.
3. A function for binding a function to a value with appropriate types. Optional<R> andThen(Optional<T> x, Function<T,Optional<R>> f) { ... }. This function has a couple restrictions on what it's allowed to do which are called the "monad laws". It's not really worth burying yourself in them. The important part is that they have the effect of requiring inject and andThen to do the absolute minimal thing that works sanely.
This really isn't complicated. It's a super-basic pattern. It keeps getting reinvented over and over in languages with first-class functions.
So why do you not hear about it outside of typed functional languages? Because very few languages give you the flexibility to work with this abstraction. In Haskell or F#, you can write code that works with any monad. In Java or Rust, you can only write code that works with a specific type. The missing abstraction capability makes the abstraction academic only. And since it's so simple, there's nothing in particular to be gained by talking about the abstraction when you can't use it.
People have made a huge deal out of monads, but they're really not complicated. Thinking they're hard or hold the secrets of the universe is like thinking the Iterator interface is hard or holds the secrets of the universe. Sure, maybe a language has some syntactic sugar to make it easier to work with them (do-notation in Haskell, for loops in Java). But it doesn't mean there's anything complicated going on.
Note the things absent from this response: IO, side-effects, purity, sequencing, basically any use case. None of them are related to the definition of monads. None of them require monads. Monad is an abstraction. It doesn't let you do anything new. It just lets you share vocabulary (and code in more expressive languages) between many disparate areas.
F# doesn't have higher kinded types, so I doubt this is true.
I found solace in telling myself "The word Monad is meaningless except for the fact it tells me this abstract thing behaves according to these laws and I can use a set of standard API's and functions on it".
Languages like Haskell provide a large API for using regular functions with Monads, combining Monads together, sequencing them in different ways, and much more.
http://stackoverflow.com/questions/2704652/monad-in-plain-en...
(For all the innovation in the training delivery of programming training there seems to be little attention paid to the pedagogy. This is not really a slur on this book (I haven't looked in detail; hence the brackets) but too many of the online training providers just use the same old ineffective curriculum they were exposed to in undergrad.)
Then you won't be doing functional programming. You will be doing "somewhat functional programming" at best.
"Anonymous strangers on the internet will tell you that what you're doing isn't "real" functional programming, but hey - at least you'll actually be programming rather than whining on message boards"
You know that this doesn't make JavaScript be a functional language, right? It still only has some parts from functional paradigm, and those are not well-fitted, so fully functional programming in JS is awkward.
Even then, I think we all understand that the OP isn't trying to be strictly pure and is simply trying to explain the concepts in a manner that those used to imperative development can easily digest.
2. No product types. You can emulate those, but it's awkward.
3. No recursion over lists. You can emulate this, but it's awkward.
4. It's difficult to write code that is efficient, yet is side-effects free. Good luck with prepending an element to a list.
About emulation, you can emulate closures on Turing machine, though it doesn't make Turing machine a functional language. Lack of the aspect is simply lack of the aspect.
And no, JS doesn't explicitly prevent functional programming (or rather, some aspects of it). It does so implicitly.
> OP isn't trying to be strictly pure and is simply trying to explain the concepts in a manner that those used to imperative development can easily digest.
It's like trying to show how to do OOP in C. It's a different paradigm than the primary of the host language, so any educational aspect will be severly diluted, to the point of being useless to anybody who doesn't already know functional programming.
Actually, I'd think that would be a super valuable to a C developer. Learning to implement OOP patterns in C would provide practical patterns that can help architect C software. For non-C developers, it'd also provide fundamentals of how OOP actually works. C developers have been implementing OOP patterns since well before C++ existed.
There's lots of resources, and practical examples of this. GObject provides an object system used by both Gnome and GTK. Check out "Object-Oriented Programming With ANSI-C" for a book on the subject.
Says who? I've taught OOP, as a concept, to people using C. It's incredibly obvious when you see it written--once you've implemented inheritance through structural composition, it's strikingly easy to reason about how traditionally OO languages handle their object models.
(This is basically what GTK does!)
2. Would probably make more sense if it were a statically typed language. Don't most dynamically typed FPL need to emulate this?
3. Got an example of it being awkward that isn't helped with ES2015?
4. (item, list) => [item].concat(list)
Pretty much how I learned OOP:
http://www.amazon.com/Class-Construction-Object-Oriented-Programming-Fundamentals/dp/0136301045
It can be nice to have language support, but it can be nice to learn a paradigm primarily as a way of organizing your program.What do you mean by no recursion over lists? I mean, sure, lists aren't a core data type in JS (JS arrays aren't lists), so list operations aren't either, is that it?
Do you mean sum types?
There are also several libraries with pure functional implementations (ex: bilby)