102 points · by eatonphil · 11y ago · 125 comments
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.
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.)
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.
"A language doesn't have to be pure to support functional programming."
This is very much the case.
However, we must chain these into useful programs somehow. Monad is the type name chosen in Haskell for the construct that does this. It's kind of simple if you work it backwards from the syntax. You want to be able to say
do
a <- readInt
b <- readInt
add a b
print
The first two can fail, rely on side effects and the last one is purely a side effect. The only pure function is add, which can't work if a or b aren't there. Monads serve as a way to represent the real-world-ness without it seeping into the add function. You can think of each line as a closure getting the next value from the previous line. So readInt returns a Maybe Int. If it returns a Nothing, the next closure is simply skipped. You can insert a check after the add, if you want to, to see if you got Nothing and alert the user, etc. However, the basic idea is that the program does not crash with a NullPointerException. We know what to do if we get Nothing. The add function doesn't need to concern itself with that.Hence, the Monad. It wraps a real world concern around a type (it has a type constructor). You must be able to make one from a concrete value that is unburdened with exceptional state (it has the unit function). You must be able to call pure functions on these monadic values without the side state seeping into the function (it has the bind function).
Edit: the reason you don't see Monads in other languages is because they're not essential to them. You can do stuff in C without Monads. To Haskell, Monads are like the Higgs boson. It's how you bind stuff together.
* Purity is not at all bizarre to the real world. If I have two apples in one pile and three in the other, then merely regarding them as the same pile is (2 + 3) very, very purely. Computers are the bizarre ones!
* "The first two can fail, rely on side effects and the last one is purely a side effect." It'd be much nicer to say that the first two are "side effecting computations with interesting return values" and the third one it the same... except we are not interested in the return.
* "The only pure function is add". I highly doubt that `add` is pure in your example! (1) this wouldn't typecheck in Haskell now if it were and (2) it'd imply that we are just throwing away the result of the addition.
* "the reason you don't see Monads in other languages is because they're not essential to them" I would challenge you to turn this exactly on it's head. The reason you don't see monads in other languages it that they are so essential to them that you cannot perceive parts without the monad.
That sounds more like fmap.
(+) <$> readLn <> readLn
The monadic part only comes into play in the last line:
(+) <$> readLn <
> readLn >>= printIt's part of what makes it monadic that the action takes an argument.
A functor is a type parameterized by another type[1], say 'a', with a function 'fmap' taking a function 'a -> b', yielding the original object except that its type is now parameterized by 'b'[2]. A monad's 'join' operation takes 'f (f a)' onto 'f a'.
On top of this, there are certain laws which must be obeyed. The functor laws amount to saying that 'fmap' can't change anything about the object (including structure) which doesn't depend on the parameter 'a', but must change everything which does depend on 'a'. The monad laws amount to saying that 'join' has a certain associative structure[3], and also that there is a left- and right-identity 'return: a -> f a'.
[1] a la Java generics, for those not into FP
[2] i.e., fmap has type 'forall a b. (a -> b) -> (f a -> f b)'
[3] Explaining exactly what this associative structure is in these terms is tricky, since 'join' as described is unary. Here's where you have to introduce the function 'bind', '(\f -> join . fmap f)': 'bind g . bind f' === 'bind (bind g . f)'. But it's really not essential; the most intuitive consequence is that Haskell's 'do' notation works like you want it to.
I've struggled with blog posts about monads countless times. Maybe I just find it easier to listen to some explanations rather than read them.
"A monad" isn't a thing, but we can ask what it takes for something to "have monad-nature" or "be a monad". For this to occur our something must be three things, a triple
(T, mu, eta)
The names are all meaningless so for the moment they just get short letters.T must be what's known as a Functor. For PLs really, though, it's even more specific. It's an "endofunctor on the type category of your language". What this means is simple
* For any (static) type `a` in your language, `T a` is also a static type.
* For any function `f` from type `a` to type `b`, `T f` is a function from type `T a` to `T b`.
If your language doesn't have static types then you can approximate this by pretending that it does. Also note that `T f` is not usually the syntax used, but it'll do for now.
Now to make a monad we take any choice of Functor `T` and give it two operations. `eta` takes values in type `a` to values in type `T a` while `mu` takes values in type `T (T a)` to values in type `T a`. In other words they give you a "layer manipulation toolkit".
They must follow laws as well, but these laws are all "common sense laws" which allow you to think of values in the following types: `a`, `T a`, `T (T a)`, `T (T (T a))`, `T (T (T (T a)))`, ... as all being the same as values with just one layer: `T a`. This is the "flatten" idea.
And there you have it! Anything at all which can be regarded as equivalent to one of these triples following this design and laws is a monad!
---
So the real question is why should someone care? The answer is simple.
Lots of things have monad-nature in a typed language. By recognizing their common nature we can (a) see them in a new light full of perhaps previously unknown similarities, (b) share terminology lightening the burden of how to use them, (c) write generic operations which work over any monad and expect them to work with each specific one in a similar way, (d) introduce new syntactic sugar which is built entirely from (mu, eta) and expect it to work similarly for every thing with monadic-nature, (e) begin to form theories and impressions of "what it means to be a monad".
The reasons (a-d) show up all the time once you recognize this pattern since monads are really common.
Reason (e) is what everyone wants to hear about but it's hard to talk about without being super arm-wavey. But I'll try.
In order to provide the operation `mu :: T (T a) -> T a` the type `T a` must be able to "internalize itself" without losing too much information. In order to follow the laws, one bit of important information is an idea of sequence or nesting—but one unique to each particular monadic triple.
In this way monads are a very, very, very general way of talking about sequencing or nesting.
What makes thins interesting is that you can see imperative languages as being about sequencing or nesting as well. If you have a listing of statements { X ; Y ; Z } then you can see { Y ; Z } as being nested in the execution context that X created and { Z } being nested in the execution context that { X ; Y } created.
This would maybe make you think that imperative languages have monad nature and indeed they do. This leads to an interesting study of questions like "For some given imperative language, what is a pure-functional representation of the monad representing it?" which sometimes has interesting answers.
What's even more interesting is that one example of reason (d) above is to introduce a syntax sugar which makes any monad look a bit like an imperative language. This leads to an interesting study of questions like "What does the imperative language for some monad X feel like?"
So if you really like imperative languages and recognize that there's a larger design space here that most have any familiarity with then monads are a good thing to keep an eye out for.
I suspect some people (not saying this author) butcher the explanation intentionally. Makes it seem like an ineffable topic that only the smartest programmer can understand.
For anyone unfamiliar, the `then` of Promises corresponds to the monadic `bind` or `flatMap` (if the given function returns a Promise) or the functorial `map` (if the given function returns a plain value).
A monad then is just the interface shared between Promises (`then` and `resolve`, collections (`flatMap` and `wrap`), etc.
The hard part for me was visualising the pattern for more complicated types like parsers (functions from strings to results) and continuations.
But there are some that do not. For instance, the "reverse state monad" would not make sense with 'bind' named 'then' since... as the name implies, state flows backwards through time in it!
Is there any reason to use monads in (let's say) Javascript rather than promises? Are there any performance gains?
A little while ago there was an article (https://news.ycombinator.com/item?id=9907435) which suggested code like
if (cond1)
return val1;
if (cond2)
return val2;
if (cond3)
return val3;
return defaultVal;
is simpler and better than if (cond1) {
return val1;
} else if (cond2) {
return val2;
} else if (cond3) {
return val3;
} else {
return defaultVal;
}
or something like that. In a certain sense this is objectively false as the second one uses fewer features than the first (a statement we can make formal using monads, but that's unrelated). I'd argue this is doubly true because whenever non-linear flow control begins to be used pervasively it is hard to know what code will be executed and under what conditions. With nesting at least these conditions are obvious.In any case, we can solve this conundrum through the existence of an Option or Maybe type which encapsulates the imperative behavior of short-circuiting failure directly and limits it's scope.
Not intrinsically, IMO. The main value of monads is the shared interface, and its utility is contingent on tools that recognise that interface.
In that respect, it's as useful as providing e.g. a `map` method for promises, arrays, dictionaries, etc. Though in my experience JavaScript rarely seems to be written with this kind of generic interface in mind (e.g. there's no coherent interface mandated between classes in the standard library).
Once you understand and fully appreciate Monads, you lose the ability to explain them to other people.
Consequently, whenever someone feels they understand Monads they are compelled to write a tutorial to demonstrate their understanding and consequent elevation to "true programmer" status. There is a large audience for these tutorials as all the "non-true" programmers struggle to reach this stage.
I certainly only wanted to understand Monads because they sounded cool, not really because I wanted to become a better programmer. Although I certainly found this to be quite a positive side-effect in my struggles to become a "true" programmer.
That definitely doesn't make it "not simple" - it's the simplicity that's the trouble :-P
They don't teach you number theory before arithmetic in primary school. Similarly, you don't need to understand monads before you use IO.
Think about it. In python there's really no syntactic sugar to place something in a container, so the concept doesn't really exist in python until you invent it using other python language primitives. So when you tell a python guy about a burrito, he really has no language analogue to think about. When I tried to learning about the maybe monad, I looked up a tutorial that taught it in python... Big mistake. I was thinking why the hell would people go out of there way to wrap that shit up in a burrito when they can just do a goddamn try exception... It made no sense to me, and even now, it still doesn't make sense for python. Only when I learned about haskell did I realize how the maybe monad makes sense for haskell.
I think most people learn about monads through haskell or any other language with a similar type system. It'd be interesting to hear peoples' experiences about how they grokked the concept.
func addMultiple(#a: Int)(b: Int)(c: Int) -> Int {
return a + b + c
}
It can not auto-curry parameters, but at worst you can wrap functions in their curried couter-parts.Erlang, for example, being functional but strict language, requires no monads. So does Standard ML. In these languages a monads would be a useless, redundant abstraction which will only clutter the code.
Example:
Valid("userId").flatMap(userId =>
Invalid("address").map(address => User(id = userId, address = address))
would stop for the address validation, because the flatMap for a Validation is specified as: def flatMap[B](f: A => Validation[B]): Validation[B] = this match {
case Valid(value) => f(value)
case Invalid(value) => Invalid(value)
}
and map for a Validation is specified as: def map[B](f: A => B): Validation[B] = this match {
case Valid(value) => Valid(f(value))
case Invalid(value) => Invalid(value)
end
And of course we can have a bit of syntactic sugar to not nest dozens of flatmaps, in Scala we use for: for {
userId <- Valid("userId")
address <- Invalid("address")
} yield {
User(id = userId, address = address)
}
Now in the main function we can handle the Valid and Invalid with pattern matching and look, we can stop the computation without throwing exceptions, which makes testing and everything way simpler.OK, in some statically typed languages which perform type-inference, there is a restrictions for homogeneity of conditionals and aggregates, otherwise all your type inference falls apart. So, to address this problem we could use data simple structures, like tuples, or we could create a new data-type. The canonical example that Nothing or Just T type. Because different branches of a conditional must be of the same type - this is the type. Also for the sake of type-consistency, it is parametrized type. In old-school languages we will just return nil, or (values ....) Semantically there is no difference.
Ideally, types and semantics should not interfere. Complicating semantics in order to satisfy a type-system is a controversial idea.
As for Monads - it is just an Abstract Data Type, nothing special, in which Semantics and Type information complement each other. It has been created to keep types consistent - a parameteized type along with two procedures.
As an old-school programmer, I used to think about types as tags, the way it is in Lisps. (Of course, I know that these tags could be arranged in categories, hierarchies, and so-called "laws" could be defined). So, in my view, this is nothing but nested type-tags. It makes it easy to view Semantics and Types separately.
In Haskell a Monad has another "function", which is, in my opinion, is the reason why it was created. Along with satisfying the type-system, it also ensures an order of evaluation in a lazy language. The semantics is obvious - you evaluate an expression, and lift (type-tag) the value back into Monad, so the whole expression has type Monad T.
OK, this parametrized type is justified in Haskell, but in other languages, in my opinion, it is a redundant decoration, not a necessity.
As a simple example, if you'll buy that by your reasoning OCaml would find monads to be a "useless, redundant abstraction which will only clutter the code", then I'd ask why both Async and Lwt are built to be monadic? Or, if you still feel that's a mistake, how you'd design them elsewise?
I've tried to explain my view in the comment above.
E.g. I can use Future for managing async-ness. I can use a system a bit like http://typelevel.org/blog/2013/10/18/treelog.html for weaving statistics collection through my computation. I use Free to express database operations that need to happen in a transaction. I can use Either to handle operations that might fail.
I can write a method that builds a report from a bunch of rows that works with any of these four contexts, because all of them form monads.
Haskell's do notation is syntactic sugar over monads which effectively allows you to write 'imperative-looking' code while still carrying a local state forward without mutation. The Wikibook[1] does a pretty good example of explaining what this looks like (though I'm guessing you already know this).
Now, obviously it is true that one of do notation's advantages is the same as any other monad usage: it allows us to explicitly sequence events in a lazy language that otherwise offers no (obviously intuitive) guarantees on evaluation order. In that sense it's nothing more than sugaring over the otherwise necessary usage of a lot of ugly >> and >>= operators everywhere in increasingly annoying indentation.
But the other thing it offers is a syntactic sugaring over carrying state forward into successive computations (like the State monad[2]), which still carries at least some useful sweetness in a language that is otherwise functionally pure, which is why F# generalized the concept even further to computation expressions[3].
Looked at another way, do notation, or something like it, can be used to sugar over something that rather more looks like the Clojure ->/->> operators, where the initial value is essentially a local namespace. Much like the threading macros, the result even appears to be doing a kind of mutation, even though it's actually doing nothing of the sort.
This kind of thing turns out to be useful for games, for instance, as the linked State monad example above does. In games we often have a main update loop, where we have to do several successive operations on our game that might change the state. We can do this a number of ways, but one way is with something like do notation, where for instance (in some hypothetical language) we might do this:
do with gameState
oldGame <- gameState
gameState <- checkInput
gameState <- tick
if gameState != oldGame
draw
And all of this kind of "fake mutation" can be handled underneath the sugar in a purely functional manner. It's something I've been meaning to put into Heresy for some time. Heresy uses continuation based loops that have a "carry value", that can be passed from one cycle to the next. It's a simple matter of some macro magic to then layer over this some syntax sugar that makes that carry value effectively a name space, that can be altered from one statement to the next, but all entirely without actual mutation underneath.You can write whole imperative, mutation-riddled languages in purely functional ones this way. There's an implementation of BASIC that runs in the Haskell do notation.[4]
[1] https://en.wikibooks.org/wiki/Haskell/do_notation [2] https://wiki.haskell.org/State_Monad [3] http://tomasp.net/blog/2013/computation-zoo-padl/ [4] http://augustss.blogspot.fi/2009/02/is-haskell-fast-lets-do-...
https://lobste.rs/s/r5oeqr/monads_in_javascript/comments/sxt...
Makes me want to use purely functional languages even less.
What do you define as useful? Reading a file and taking the first line maybe? Here's what you need to know:
Start ghci (I'm using stack[0], if you don't have stack you can also just use `ghci` here).
cody@cody-G46VW:~$ stack ghci
Using resolver: lts-2.16 from global config file: /home/cody/.stack/global/stack.yaml
Configuring GHCi with the following packages:
GHCi, version 7.8.4: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> import Control.Applicative ((<$>))
Prelude Control.Applicative> readFile "/etc/issue"
"Ubuntu 15.04 \\n \\l\n\n"
Prelude Control.Applicative>
Now we are going to use the $ sign which allows you to avoid extra parenthesis. Prelude Control.Applicative> let add x y = x + y
Prelude Control.Applicative> let subtract x y = x - y
Prelude Control.Applicative> add 5 (subtract 3 5)
3
Prelude Control.Applicative> -- now using $
Prelude Control.Applicative> add 5 $ subtract 3 5
3
Prelude Control.Applicative> -- what's the point of me teaching you the $ operator?
Prelude Control.Applicative> -- it's similar to one we'll use to apply our lines function to what readFile returns
How can we split the file by newline? Prelude Control.Applicative> (fmap lines (readFile "/etc/issue"))
["Ubuntu 15.04 \\n \\l",""]
From there, how can we get the first item? Prelude Control.Applicative> (fmap head (fmap lines (readFile "/etc/issue")))
"Ubuntu 15.04 \\n \\l"
The duplication of fmap is getting kind of tedious to me. We can use function composition to avoid it. I'll use the add and subtract function definitions from above, but I'm sure it's obvious what those do. Prelude Control.Applicative> let addFiveSubtract3 x = (add 5 . subtract 3) x
Prelude Control.Applicative> addFiveSubtract3 0
Now you know (hopefully) how function composition works, how can you use it for real stuff? Prelude Control.Applicative> -- back to reading files and stuff
Prelude Control.Applicative> fmap (head . lines) (readFile "/etc/issue")
"Ubuntu 15.04 \\n \\l"
Remeber that seemingly pointless detour to teach you what $ does? Let's try using that. Prelude Control.Applicative> fmap (head . lines) $ readFile "/etc/issue"
"Ubuntu 15.04 \\n \\l"
There is an infix version of fmap called <$> which you might notice resembles $ with the addition of square brackets, kind of like it's in a box or something. Try removing `fmap` and replacing `$` with `<$>`. I'll wait here.....
....
....
....
....
Done? Alright, here is the solution just in case:
Prelude Control.Applicative> (head . lines) <$> readFile "/etc/issue"
"Ubuntu 15.04 \\n \\l"
We can actually get rid of the parenthesis on the left hand side of <$> like so: Prelude Control.Applicative> head . lines <$> readFile "/etc/issue"
"Ubuntu 15.04 \\n \\l"
Now how can we print it out? Well, let's see what our type is: Prelude Control.Applicative> :t head . lines <$> readFile "/etc/issue"
head . lines <$> readFile "/etc/issue" :: IO String
Something to know about Haskell is that it's okay to be naive and pick functions whose type signatures look like they do what you want. There are even search engines[1][2] that take type signatures and give you functions.So what is the type of putStrLn?
Prelude Control.Applicative> :t putStrLn
putStrLn :: String -> IO ()
How could we go from `IO String -> IO ()`? Well, IO is a Monad (thing which follows some rules as defined by typeclasses). A monad defines a few things as you can see here:http://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude...
But remember, we aren't interested in intimately understanding all that stuff... just in getting our functionality working. Maybe later we can circle back and figure stuff out at a deeper level.
The first function defined is >>=, whose type is:
(>>=) :: Monad m => m a -> (a -> m b) -> m b
What was that type we needed again? Let's compare these two: (>>=) :: Monad m => m a -> (a -> m b) -> m b
If we look at the type of our function getting the first line of a file: head . lines <$> readFile "/etc/issue" :: IO String
We see that it can fit into the m a part of this: (>>=) :: Monad m => m a -> (a -> m b) -> m b
IO String
Keep in mind that m means Monad, as is specified in the typeclass constraint to the left of `=>`.Now we can specialize our type signature to:
(>>=) :: Monad m => IO String -> (String -> IO b) -> IO b
What's an `IO b`? `a` meant anything so what does `b` mean? `b` actually means anything too, but a was already taken in the earlier part of the type signature.If we look at the type of our putStrLn function:
putStrLn :: String -> IO ()
You might notice it fits into the second part of our new specialized type signature: (>>=) :: Monad m => IO String -> (String -> IO b) -> IO b
String -> IO ()
aside: () is kind of like void, at least that's how I think of it. It's actual name is unit.So our full function is now:
(>>=) (head . lines <$> readFile "/etc/issue") putStrLn
Let's try it out: Prelude Control.Applicative> (>>=) (head . lines <$> readFile "/etc/issue") putStrLn
Ubuntu 15.04 \n \l
Cool, now notice that I put parenthesis around the infix function to make it a prefix function. Let's take those parenthesis off and use it as a proper infix function: Prelude Control.Applicative> (head . lines <$> readFile "/etc/issue") >>= putStrLn
Ubuntu 15.04 \n \l
Take out superfluos parens: Prelude Control.Applicative> head . lines <$> readFile "/etc/issue" >>= putStrLn
Ubuntu 15.04 \n \l
There is a flipped version of >>= called =<< that is easier to read in this case to me: Prelude Control.Applicative> putStrLn =<< head . lines <$> readFile "/etc/issue"
Ubuntu 15.04 \n \l
We could have also used do notation and the `<-` or "draw from IO to variable on the left, taking appropriate actions as defined by the Monad context you are in in the case of a failure". So if you are in the Maybe monad's context, a failure will cause a break (using imperative terms) and return Nothing.The example using do notation:
Prelude Control.Applicative> putStrLn myLine
Ubuntu 15.04 \n \l
There, now you know how to use monads and functors to some degree for a real problem and know the minimum knowledge (as far as I can tell) necessary. Why do all of this just to read the first line of a file?Now that you know how the machinery works it's pretty simple and gets you composability and referential transparency.
Want to know more about Functors and Monads (maybe even applicatives O_o)? Check out Functors, Applicatives, And Monads In Pictures[3].
0: https://github.com/commercialhaskell/stack
1: https://www.haskell.org/hoogle/
3: http://adit.io/posts/2013-04-17-functors,_applicatives,_and_...
Monads are a fantastic way of handling errors, composing parsers, handling concurrency, parallelism, callbacks, and many other non-IO related things.
It is a trivial pattern. But a powerful one.
> 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?
Yes - the best way to build complex things is out of simple primitives. A lot of the time, making a custom type be a monad simplifies the logic - that is, you'd want to implement the monad operations (and support do notation) anyway. Calling them by their standard names makes it easier for other people to read your code, and being able to use generic library functions like traverse (which work for any monad) with your custom type is just a bonus.
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).
:(
Wonder why the author enabled st but not ct, though...