8 ms·
Mostly Adequate Guide to Functional Programming in JavaScript
- dozzie 11y ago> We'll use the world's most popular functional programming language: JavaScript Then you won't be doing functional programming. You will be doing "somewhat functional programming" at best.
- ExpiredLink 11y agoUndoubtedly, JavaScript triggered the functional hype, not Haskell or Clojure.
- rubiquity 11y agoI would say it's a joint mindshare from all the various functional families (Lisp, ML, Erlang). After all, what kind of programmers do you think wrote the functional libraries that led to the "functional hype" in JS in the first place?
- ExpiredLink 11y agoJavaScript's functional hype was initiated by Douglas Crockford.
- untog 11y agoYou're right, they should have added a caveat: "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"
- dozzie 11y ago"Of course those random strangers will not know several languages of different paradigms, and will not be programming themselves, in opposite of what you are doing." 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.
- taco_emoji 11y agoWhich aspect of the functional programming paradigm cannot be done in Javascript?
- dickson 11y agoTail recursion optimization, lazy evaluation
- sabarjp 11y agoTail recursion optimization is in ES6. Lazy Evaluation is provided in multiple libraries, including lazy.js. There are also several libraries with pure functional implementations (ex: bilby)
- Lazare 11y agoIf you're listing a core language feature as something that "can't be done in that language", you may not understand the language as well as you think.
- Kutta 11y agoPolymorphic return types, most notoriously. But also anything that's complex enough so that dynamically typed implementations become unfeasible or effectively unmaintainable.
- lojack 11y agoIs there a reason why you can't do functional programming in JavaScript. Unless I'm mistaken, there isn't anything about JavaScript that explicitly prevents you from doing functional programming. 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.
- dozzie 11y ago1. No pattern matching. Libraries can't help here, it's a syntactical and semantical issue. 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.
- dragonwriter 11y ago> No recursion over lists. You can emulate this, but it's awkward. 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?
- dozzie 11y agoIt's not "is that it". Single-linked lists of specific characteristics (access times, construction times and stuff like that) are one of the few core elements of functional programming.
- 11y ago
- noelwelsh 11y agoNice illustrations, and a worthwhile project. I'd like to know what has motivated the sequence of topics, as things I consider fundamental (e.g. structural recursion) don't seem to get a look in. This is judging just by the TOC. (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.)
- crazygringo 11y agoFor a long time I've been looking for a guide to functional programming, applied to common real-world web examples, but still can't find one. 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.
- Retra 11y agoFunctional programming is not for back-end web programming or front-end web programming. That's like asking if calculus is for making better nails or for making better screws. Or if a 68K processor is for doing taxes or for doing word processing. 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.)
- edvinbesic 11y agoFor those of us non-yet enlightened, I keep reading these kind of comments and walk away more confused. 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.
- monknomo 11y agoI have only tried FP a little bit, but I personally found value in non mutating data and removing side effects, even in the portions of my code that are OO. 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...
- n0us 11y agoSomething I've been wondering for a long time that no one seems to be able to explain is "what the fuck is a monad?" and why is this seemingly the one question about programming that is inadequately answered
- tdees40 11y agoIt's a pattern that recurs in lots of different programming environments. It's an abstract pattern, so it confuses people who've never encountered them, and then they go out and read a bunch of terrible monad tutorials which obscure what's really going on. 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.
- Procrastes 11y agoI think this comes closest of anything I've read to answering your question directly. http://stackoverflow.com/questions/2704652/monad-in-plain-english-for-the-oop-programmer-with-no-fp-background/2704795#2704795 http://stackoverflow.com/questions/2704652/monad-in-plain-en...
- deleted 11y ago[deleted]
- chowells 11y agoI'm willing to bet you've read 10 plain-english perfectly-adequate explanations of monads that explain them fully, and you've rejected them because they don't seem hard enough. 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.
- elliotec 11y agoAlso see Functional JavaScript [1] by Michael Fogus. [1]http://shop.oreilly.com/product/0636920028857.do http://shop.oreilly.com/product/0636920028857.do
- amelius 11y agoDoes it treat lazy evaluation? Also, how efficient will the resulting code be, if these conventions are used?
- Roboprog 11y agoThe author should probably have mentioned in the Currying section that it's roughly analogous to what OOP people call dependency injection. 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.
- thesagan 11y agoThank you for that analogy, I think you might have saved me a bit of time wrapping my head around the FP "paradigm".
- cnp 11y agoSeriously impressed with the communicability of your examples. A+, will share this around.