26 ms·
Monads in JavaScript
- amyjess 11y agoWell, those are some fancy ligatures. Wonder why the author enabled st but not ct, though...
- ghik 11y agoPLT_HULK would have something to say about it :) https://twitter.com/plt_hulk/status/397822619736870912 https://twitter.com/plt_hulk/status/397822619736870912
- mlitchard 11y agoI feel like this rush to adopt functional language features in non-functional languages is like deciding to shoehorn a jet engine onto your hot-air balloon. Yes, it can be done but ... see PLT_HULK.
- _davidchambers 11y agoThese two functions are equivalent: const f1 = function(s) { let data; try { data = JSON.parse(s); } catch (err) {} if (data != null && data.a != null && data.a.b != null && typeof data.a.b.c === 'string') { let x = parseFloat(data.a.b.c); if (x === x) { return x; } } return null; }; const f2 = R.pipe(S.parseJson, R.chain(S.gets(['a', 'b', 'c'])), R.filter(R.is(String)), R.chain(S.parseFloat), S.fromMaybe(null)); Note that in the first function we have an unsafe expression, data.a.b.c which we must guard with null/undefined checks. Unsafe expressions can easily get out of sync with their corresponding guards. We can apply functional programming concepts to JavaScript code to obviate the need for null/undefined checks. The fact that we can't have all the benefits of FP in JS shouldn't dissuade us from taking advantage of the ideas which are applicable.
- comex 11y agoLess as a real argument than as devil's advocate, here's a shorter non-library version: function f1(s) { try { let data = JSON.parse(s); let x = parseFloat(data.a.b.c.substr(0)); if (x === x) return x; } catch(e) {} return null; } ...ok, it's a bit golfy, and in JavaScript you don't get much control over exception catching. But in general, exceptions can be used like an implicit Maybe/Either monad, just as mutability is an implicit IO monad. (Also, you picked an odd task - it's unusual to expect a float to be represented as a string in a JSON object, and a check that rejects NaN but accepts weird floats like Infinity is not terribly useful.)
- _davidchambers 11y agoIt's a contrived example, certainly. Your counterexample is informative. I hadn't thought of exceptions in this way. The downside of putting everything in a `try` block, of course, is that we'll potentially catch exceptions arising from a bug in our code which should crash our program.
- mlitchard 11y agoFood for thought David, thanks!
- dragonwriter 11y ago> I feel like this rush to adopt functional language features in non-functional languages is Very few languages in use are fairly described as "non-functional"; pretty much any structured programming languages that supports function pointers supports the functional paradigm. A language doesn't have to be pure to support functional programming.
- dllthomas 11y agoWithout closures, or something that well approximates them, it seems hard to say a language "supports the functional paradigm". You can write functional code in C, but beyond very simple things you're implementing most of the machinery yourself. "A language doesn't have to be pure to support functional programming." This is very much the case.
- nextstepguy 11y agoTaking that (free) class on coursera was an eye opener on all the things that are discussed in this article. Highly recommended: https://www.coursera.org/course/reactive https://www.coursera.org/course/reactive
- tel 11y agoHere's a thing I wrote when this was submitted to Lobste.rs: an implementation of the continuation monad which was elided. https://lobste.rs/s/r5oeqr/monads_in_javascript/comments/sxtbia#c_sxtbia https://lobste.rs/s/r5oeqr/monads_in_javascript/comments/sxt...
- krat0sprakhar 11y agoLove Javascript and want to learn FP? Checkout this book - https://github.com/DrBoolean/mostly-adequate-guide https://github.com/DrBoolean/mostly-adequate-guide. I stumbled upon it last week and I've found it to be quite approachable (although I haven't yet read the section on Monads).
- findjashua 11y agosearch in repository + pattern matching --> no results :(
- krat0sprakhar 11y agoNot sure I understand - are you looking to learn about 'pattern matching' in Javascript and couldn't find anything in the book?
- findjashua 11y agocorrect
- weavie 11y agohttps://github.com/natefaubion/sparkler https://github.com/natefaubion/sparkler
- kriro 11y agoI've really enjoyed "Functional JavaScript - Introducing Functional Programming with Underscore.js". I almost didn't get it because the use of underscore was a bit of a concern (the library is great but I felt I wanted to learn FP with "pure" JS). It was a fairly big step up from the intro to JS I read before (Eloquent JS) but it's a fantastic book. Jam packed with good stuff. I think the writing is a bit dense at times but the content is gold.
- eatonphil 11y agoI came to an understanding of monads the other day thinking about fail-and-reverse-on-error applications like messing with the filesystem. I have an example of this (and a simple implementation in OCaml) if it helps you [0]. After my "breakthrough", I've been seeing monads everywhere; everything is a nail. [0] https://github.com/eatonphil/monad https://github.com/eatonphil/monad
- plaid_dev 11y agoWe've leaned on this functional JS library to make JS more type safe (https://github.com/plaid/sanctuary https://github.com/plaid/sanctuary). Heavily borrows Monads and other FP concepts.
- soroushjp 11y agoVery powerful addition to JS. Definitely using this in my next project.
- erikpukinskis 11y agoAm I crazy that I never understood the point of talking about monads? It just seems like a trivial pattern. It's like having a Subroutine Pattern, or a Variable Assignment Pattern. I'm all for investing in better primitives, but do these kinds of libraries really help vs implementing them from scratch with language primitives inside your (inevitably more complex) domain code?
- pubby 11y agoI suppose it's nice to have a bunch of generic monad functions already implemented for you. Stuff like do-notation, applicative, sequence, mapM, join, etc.
- codygman 11y agoThat, the guarantees you are afforded by the monad laws, composability, and how generic solutions can be.
- 5outh 11y agoThe big problem with monad tutorials is that you can't talk about them without understanding the motivation behind them, and that comes from purely functional languages (i.e. Haskell). When you're not allowed to touch IO, use `null`, exceptions don't exist, there is no global state, and all of these things have a common pattern to them, then you can motivate their use and talk about them. In my opinion, there isn't much of a point in talking about them without those things. There are some neat tricks (`flatMap` etc...) but without proper motivation, it's not likely to stick, and the idea seems relatively useless.
- agumonkey 11y agoGreat point, most are removing the force behind the emergence of the pattern. To add insult to injury, they explain it magister, by throwing concepts first, instead of bottom up, like non Haskell tutorials do (javascript, elisp, ...) that don't have advanced type system / Monad 'a, that blurs the mind, only choreography of a bag of lambdas.
- 11y ago
- debacle 11y agoI detest how everyone always takes monads, a quite simple concept, and completely butchers the explanation. I think it's likely in large part a reason for a lack of their acceptance and use.
- braythwayt 11y agoCrockford’s Paradox: Once you understand and fully appreciate Monads, you lose the ability to explain them to other people.
- bunderbunder 11y agoThis might actually be generalizable to any design pattern of sufficient utility.
- pekk 11y agoIf you can't explain it, it's probably not such a great idea as you think it is.
- stingraycharles 11y agoI think that depends very much upon the audience. There are quite a few great ideas out there that are difficult to explain: try explaining the theory of general relativity to your mother, for example.
- crimsonalucard 11y agoI recently grokked monads, only to realize that monads are just a special case of something more general called arrows. waah.
- dschiptsov 11y agoIn a strict (as opposed to lazy) non-functional language monads make no sense. Write two statements which uses a temp variable on the same line, separated by a semicolon - this is your monad.
- crimsonalucard 11y agoNo way. While I do agree monads don't make sense in some imperative languages, writing two statements on the same line is not a monad.