161 points · by bern4444 · 5y ago · 231 comments
It makes no sense at all to try to explain that stuff in a language lacking higher kinded types. All you can do there (without awkward encodings) is creating instances of those abstractions. You can't create the abstraction as such!
A quite straight-forward explanation of the "monoid in the category of endofunctors" thing can be found here:
https://blog.rockthejvm.com/monads-are-monoids-in-the-catego...
Even the linked explanation is a "quite 'simple' one for that topic" it's still way more involved than what was shown in the article we're discussing here. That Scala stuff is actually correct, this one here isn't even close.
Sorry for the quite negative comment but imho there isn't anything else to add. Before writing a blog post about something one should get at least some basics. Things like: I need HKTs to express functors and such…
As I didn't see the given link here I think my comment makes a useful contribution even it doesn't bring anything else to the table; besides some rage about "very wrongly explained math". :-)
In particular there is an unwarranted leap here. If `numToStr` is a functor, then `addOne` (the function that just adds one to an integer) should be an endofunctor. So what's the monad?
Yet all of a sudden the article jumps to talking about `Array` as an endofunctor! Which is most definitely not a function like `numToStr` or `addOne`.
So which is it?
In particular,
> Of course, as we saw above, Arrays support a map method which allow us to transform the values of the array but do so in a way that returns an Array (the same type as the starting type), making them endofunctors.
Makes no sense combined with `numToStr`. What exactly is the `map` function for `numToStr`?
It turns out you can unify both of these notions, but you need the language of category theory to do it. But that's overkill for FP. So generally in FP a functor is just a type constructor (a type that takes another type as an argument e.g. `List<A>` or `Option<A>` or `Future<A>`) with an associated `map` function that obeys the "law" that `map`ing the identity function does nothing.
The full category theory definition requires a bit more exposition than just thinking of things as sets and functions. In particular you need to talk about two levels of mappings: mappings between categories, which are functors, and mappings between functors themselves, which are natural transformations. A monad is then a functor from a category to itself with two associated natural transformations. If the functor and natural transformations are taken as objects and arrows/morphisms in a category itself, then it forms a monoid. This is why we can also think of a monad as a monoid.
This sort of "category-stacking" where mappings between categories are treated as categories themselves where we can then further discuss another level of mapping between them, is the core of category theory.
I've started to call it "fractal math". Not to be interpreted as the mathematics of fractals, but rather as mathematics which is itself structured as a fractal (metaphorically speaking, of course).
Array is a monad. Then what's the function that takes an array and returns another? Is it map? That can't be because map takes two parameters, not one: the array and a function that it will apply to every element. Something is missing in the explanation.
And why is Option a monad? What's the associative function that takes two options and returns another Option?
Practically, the additional function that monads support is usually called bind and looks like: Array a -> (a -> Array b) -> Array b
This is different from map which is: Array a -> (a -> b) -> Array b
Notice how in map, your function returns a value that isn't lifted in the monad. The bottom one is a functor, the top one is a monad. Functors let you visit an array at every element. Monads let you visit an array and produce a new array each time and they internally decide how they will recombine those values.
This is a bit silly for Array, you just concatenate the outputs. But is more interesting for Option.
map for Option looks like: Option a -> (a -> b) -> Option b
It says "If there's anything in my Option, apply this function to it, otherwise there's still nothing there"
bind for Option looks like: Option a -> (a -> Option b) -> Option b
It says "If there's anything in my Option, run this computation. This computation can also return an option". In this sense, it lets you string together computations that each produce optional values. The whole computation will fail if any part fails. Something that is very useful!
Contrary to this post, merely being a functor and a monoid does not make something a monad; for example any arbitrary monoid (say, the integers) could be considered an applicative via Const, but is not a monad. Or many other applicative-but-not-monads have monoidal structure, e.g. ZipList.
Things could be headed off early where the blog defines a monoid. The definition given is roughly what the average mathematician would call a monoid, but a category theorist would complain saying that it only defines a monoid in the category of sets.
But monads are not monoids in the category of sets. They are monoids in the category of endofunctors! So the blog post is going off the rails from here on.
Yet you didn't say how exactly different. I understand I probably need to know category theory for that, yet nevertheless OP's post was useful, fulfilled some curiosity, but your comment didn't, besides leaving feeling "it's complex", sorry.
I'd really appreciate if someone one day wrote as clear explanation of monads as OP's, but at the same time staying correct.
If you're asking about monads in general, I think trying to understand the generic concept before understanding a bunch of concrete examples is the problem. https://m50d.github.io/2013/01/16/generic-contexts was my effort at explaining applicative functors (which are not quite monads, but monads are a fairly small extension of them) "from the bottom up", starting with some useful concrete things that happen to be applicative functors, and discovering that abstraction.
A functor has a `map` mechanism, which takes a value A and a function B, and returns something that has the same type as A. A simplistic example of a "mappable" that isn't a functor is `const map = setTimeout`: it technically take a value A (the time) and a function B, but `map(fn1, map(fn2, 1))` is semantically nonsensical even though all the types technically align and the code runs (because the effective "type" of the return value does not use milliseconds as a unit of measurement, and effectively causes undefined behavior).
A monad, in addition to being a functor, must also not have extra funky semantics. A example of a functor that isn't a monad is `Promise`. Imagine we did this:
TimeSequence = Promise
TimeSequence.of = TimeSequence.resolve
TimeSequence.prototype.map = TimeSequence.prototype.then
t1 = TimeSequence.of(1) // t1 has type TimeSequence<number>
t2 = t1.map(v => v * 2) // t2 has type TimeSequence<number>
// BUT
t3 = t2.map(v => TimeSequence.of(v)) // t3 has type TimeSequence<number>, NOT TimeSequence<TimeSequence<number>>
The Array equivalent is: SpaceSequence = Array
a1 = Array.of(1) // a1 has type SpaceSequence<number>
a2 = a1.map(v => v * 2) // a2 has type SpaceSequence<number>
a3 = a2.map(v => Array.of(v)) // a3 has type SpaceSequence<SpaceSequence<number>>
a4 = a3.flat() // this is a separate operation to get a SpaceSequence<number> out of a3
Here, Array is "monadic" because it has both map and flatMap as separate operations. Promise conflates the two, hence it's not monadic.(Note: I say Array is "monadic" in quotes, because this is only true if we constrain its uses to patterns that conform to monadic laws. If you do `array.map(parseInt)`, that's valid JS, but as far as monads go, all bets are off!)
Also, note that I renamed a bunch of methods (resolve => of, then => map) and called things `Sequence`s. This is the value of functional orientation as it pertains to programming: when we say we've implemented monadic TimeSequence and SpaceSequence, in practical terms that means that I can write code for one type and reuse it for the other type because both follow the same semantics within one larger, common context. It's a lot easier to say "these implementations are not monadic" than it is to say "Promise-based logic is not compatible with Array-based logic because the method names are all different and the semantics of flattening Promises of Promises don't match the semantics of Arrays of Arrays (or Streams of Streams, etc)".
If this is still too abstract, here's an application: suppose I'm writing a task runner that takes tasks and runs them in parallel (but queues once we reach a parallelization limit). I can serialize this representation in space by turning a array of arrays into JSON. But I can also represent this as a grid of timings (meaning, for example, I can write shared code to iterate over both representations, rather than hard-coding different implementations for each type of grid)
Now, you could make an argument that in isolation and within some artificial constrainst, both Array and Promise are monadic (i.e. Promise<Array<number>> works just fine), but saying that's monadic is basically pedantic wankery, since for practical purposes, you can't arbitrarily write code against a specification to abstractly treat promises and arrays as an implementation of a common abstraction (e.g. a sequence of some sort)
Not quite. You've come up with a great example of a problem with JavaScript Promise, but the problem is actually that it isn't a functor (it violates the composition law, for example).
https://twitter.com/randyshoup/status/992773186239516677?lan...
Feynman: I'll prepare a freshman lecture on it.
He came back a few days later to say: I couldn't reduce it to the freshman level. That means we don't really understand it. https://www.quora.com/What-did-Richard-Feynman-mean-when-he-...
[1] https://ncatlab.org/nlab/show/monoid+in+a+monoidal+category
Sometimes it makes me mad that so much confusion (and as another commenter put it, gatekeeping) has been sown in FP circles through the invention of pointlessly-obfuscated terminology for everything (and through - among many in those circles - a lack of interest in connecting the very simple dots that would allow masses of people to understand these concepts). It's like when the medieval Catholic Church refused to print a bible in anything but Latin so that they'd remain the sole authority on its content.
Kudos to the OP for cutting through some of that, but shame on those who maintain this status quo.
Edit: assuming it really is (roughly) that simple. Some in the comments have suggested parts of the OP were wrong (assuming they aren't just being pedantic), so I'm curious to see discussion.
No. I don't know why the article talks about ordinary functions on values as if they're functors. They're not (or at least, not in a nontrivial way; you could come up with a silly, useless way in which they are, but that's not what anyone's talking about). Sorry, but it's the article that's misleading you here.
Roughly speaking, in the programming context, a functor is a generic type with a map operation. E.g., arrays; you can map a function over an array by applying it to each element.
Since there's only one category in play here, these functors are endofunctors of that category; one doesn't normally say "endofunctor" in this context since it doesn't convey any additional information. (As opposed to "a monad is a monoid in the category of endofunctors", where you want to specify that, because that statement is true beyond just the programming context.)
The whole type thing is just something Haskell does, it's not something that's meaningful for general categories.
No.
> And an endofunctor is just one of those where the argument type and return type are the same?
Yes - "endo" means that in general. E.g. endomorphism.
> Sometimes it makes me mad that so much confusion (and as another commenter put it, gatekeeping) has been sown in FP circles through the invention of pointlessly-obfuscated terminology for everything (and through - among many in those circles - a lack of interest in connecting the very simple dots that would allow masses of people to understand these concepts). It's like when the medieval Catholic Church refused to print a bible in anything but Latin so that they'd remain the sole authority on its content.
> Kudos to the OP for cutting through some of that, but shame on those who maintain this status quo.
> Edit: assuming it really is that simple. Some in the comments have suggested parts of the OP were wrong, so I'm curious to see discussion.
The precise terminology is vital; it's how we avoid these errors when talking about this very abstract stuff. Given that the OP is very wrong, precisely because of the kind of attitude you've taken here, I hope you'll take this opportunity to reconsider your views.
Your behavior is precisely the behavior that someone new to FP would see and say "Hard pass on that", which goes into the greater problem of FP being unapproachable to beginners because of the unnecessary gatekeeping. If you cannot communicate with a beginner in language they understand, A.) you don't really understand it either, B.) you're just pushing them away from whatever you're advocating.
This is true, but the problem is that people will always prefer the explanation that is, as the saying goes, "simple, neat, and wrong" over the explanation that is more complicated, especially if they (and possibly the person explaining) aren't aware that the simplified version is wrong. Even if one starts from an accessible viewpoint, any concept that is worth isolating as a concept will involve some difficult step in its exposition, and it is at that step that the person seeking to understand—not the explainer—has to decide whether to stick with the explanation despite the difficulty, or to be satisfied with an easy and wrong explanation.
You could not really explain JIT compilation to someone not knowing anything about computers, could you?
From the ancient Greek "endo" meaning "within/inside" (as in "within the same group of things").
See also endogenous (endo + genesis, the latter the ancient Greek for born), meaning "born/created inside".
No, although a pure unary function could be viewed as a functor, the other direction doesn't hold.
The common FP definition of a functor is anything that supports a notion of `map` (subject to the restriction that `map`ping the identity function does nothing, this is why a Functor is slightly more than just a Mappable). This is not a unary function although map takes a unary function as an argument.
The more general mathematical definition is a mapping between categories. Categories are sufficiently general that you can view almost anything as a category, which is why a unary function can be thought of as a functor (because a functor can be a mapping between categories that happen to be sets).
But a functor is both more general than a unary function and, in a certain sense, preserves more structure than a function, since it must preserve the structure of the underlying categories whereas functions generally only care about sets.
Explain that again?
ie: say I have some value `f` that is a functor. If I call `map identity f` I should always get back `f`. The mere existence of a `map` function doesn't imply this law holds.
The identity function always returns it's argument unmodified. (identity x = x)
(Now, in Haskell the type system does not encode that law, but not following it would be breaking the interface.)
If this explanation doesn't make sense or you need more examples I'm happy to expand
EDIT: Both me and grandparent forgot another law for functors. They also need to preserve composition.
fmap (f . g) == fmap f . fmap g
In english, if I combine the functions f and g and map them, it should be the same as if I first map g and then map f
interface Mappable<A> {
// Interfaces don't quite cut it here, because you want
// `map` to return a specific implementation of
// Mappable, not a general Mappable, but we'll let that
// slide for the purposes of exposition
map<B>(f: A => B): Mappable<B>
}
class MyWeirdMappable<A>(val myCounter: Int, val myValue: A) implements Mappable<A> {
// Notice the return type is MyWeirdMappable not
// Mappable, as mentioned earlier
map<B>(f: A => B): MyWeirdMappable<B> {
if (myCounter == 0) {
return this
} else {
return MyWeirdMappable(myCounter + 1, f(myValue))
}
}
}
Although this fulfills the contract of `Mappable`, it's not a `Functor`, because `map(identity)` doesn't always return the same (or equivalent) `MyWeirdMappable`.So, to make this absolutely clear, a monad is a type constructor in functional programming. This is why I personally prefer the more “creative” explanations of monads, because they attempt to explain what the monad is doing to the original type: adding context, or the possibility of a null value, or multiple values, or a probability distribution over values, etc.
Now explain what a "type constructor" is, otherwise these words are worthless.
For example, in C, if you have any type Foo, the pointer operator * will give you a new type Foo*.
Another example: in Haskell, Maybe is a type constructor, since it takes a type parameter a (Maybe a). So 'Maybe' is a type constructor, but 'Maybe Int' is a type.
So a type constructor is like a function, but it operates on types, not on values.
List<Integer> is a type.
List<T> is a type constructor.
In order to get a real type from a type constructor, you need to "pass it type parameters". In the example above, you need to say that T is Integer.
Values are things. Concrete. Since we are manipulating computers, a value is really just some abstract symbols--1s and 0s occupying a slot in memory. The meaning of the symbols exists on a higher level, what we usually call semantics.
Types are a well-studied method to attach semantics to blocks of otherwise meaningless (but concrete!) symbols. By declaring a variable (which is just a pointer to a memory block containing arbitrary symbols) is of type Int, we are establishing that in the context of the program, the symbols occupying that memory block are to be interpreted as the encoding of an integer.
Functions are transformations of values. They manipulate concrete things to produce other concrete things. By specifying the input and output types, we ensure that the transformations applied by our functions are only used on the right kinds of things, and we also know what kind of thing we will get out of the function. Mind you, these things are still all just arbitrary symbols in blocks of memory, but now we know how to semantically interpret them based on the function's specification.
Type constructors are also transformations, but of types. That is, we use type constructors to modify or enhance the semantics of a basic type. Functors are essentially type constructors that extend function semantics as well: if F<-> is a functor, then you can "lift" any function from type A to type B into a function from type F<A> to type F<B>. (Note that I'm using the commonly recognized "generic type" angle bracket notation to deliberately avoid the confusion of Haskell's pedantically minimalist syntax.)
I think this description provides a much more intuitive path to the understanding of, say, a list as a functor. A "list" is a generic structure that can be applied to any semantics, evident in the phrase "list of X". The preposition "of" makes it clear that this is a semantic extension of whatever kind of thing that X is. Furthermore, there is an obvious way to lift functions: just apply the function to each element of the list, and collect the results in a list. Bam! There's a functor. This is starting to feel like blog post territory, but I'll forge ahead...
An important point here is that the "semantic structure" that type constructors add to a basic type has to come from some extra data that is used when defining the type constructor. In the case of functors, we have to actually describe an algorithm that implements the lifted function in terms of its basic version (as we just did for lists).
So a monoid is also a type constructor, and it must come along with a description of the monoidal product: For type M<A>, we need to describe a function (the monoidal product) which takes two A's and returns another A. We must also identify a specific value within type A that serves as the identity element. Now, to actually be a monoid, the monoidal product and identity element must satisfy some laws, but in general proving the laws are satisfied by a given constructor is outside of the capabilities of our type syntax. This is a step up from the functor type constructor, which needs only a valid implementation of the lifting function (called `fmap` in Haskell) in order to establish that we have actually created a functor.
In any case, to arrive at monads we don't actually combine the functor and monoid type constructors; instead we gently introduce monoid semantics on top of a functor. We do so by making the functor type constructor itself act like a monoidal product, so that repeated applications of the type constructor don't create "nested" versions of the semantics, they just stop at the first level instead. Lists are again a very straightforward example of this: List<A> is a list of things of type A, and List<List<A>> is a list of lists of As, and there is an obvious way to bring the list of lists back down to just a list: flatten it.
...okay maybe I'll stop there, at least for now.
A functor is a PAIR, please notice the emphasis, of a type constructor F and a map function with the following signature: a -> b -> f a -> f b.
Its not a type constructor, it's a pair of two things, the type constructor AND its map function.
Now that we said what it is we provide the usual simple example of Array, Record or Option, show the type constructors and show how we map them.
Is it really so hard to grasp starting from definitions rather than examples and contrived blogs?
I wish people understood that fp is much easier to understand by reading definitions.
The real landscape of its adoption begs to differ. For the great majority of people, examples and analogies are fantastically more efficient for communicating ideas than building up from first principles. You get to re-use existing mental machinery, intuition, etc, until enough experience has been gained to refine it.
(a -> b) -> F a -> F b; the parentheses are critical. I don't fully disagree with your point, but if you're going to emphasize rigor and definitions, it would be wise to make sure you're not setting people on the fence up for mistakes akin to those in the original post.
(You also called it `F` and then used it as `f`.)
I wish more FP writers understood that not everyone has the same neurotype, and "easier to understand by reading definitions" is far from a universal statement.
So why can't we just call the damn things 'Type constructors'?
So basically it is just a parametric type such as List<T> which has a type constructor so you can get a concrete type (eg List<String>), a map function which takes a function f: A => B and and turns it into a function List<A> => List<B>, and a "flatten" function with will turn a List<List<A>> into a List<A>.
The last part is what allows "flatMap" which takes a function f: A => List<B> and turns it into a function List<A> => List<B> and is really just a shorthand for doing map and then flatten.
This is why people say "a monad is a monoid in the Category of endofunctors" as a joke whenever anyone posts an unnecessarily complicated explanation. This is the biggest and most visible flashpoint between people who don't understand, and the people who don't understand why they don't understand and think that defining things in terms of other things that you also don't understand is a viable strategy.
I share the sentiment that FP jargon can be impenetrable to the uninitiated, but the same can be said about programming jargon to non-techies: it may sound like gatekeeping to talk about "closures" but there's technical reasons why closures are called closures and global state being accessed by functions are not.
The same goes for FP. Saying `val => val + val` is a functor because it maps numbers to numbers isn't really correct: you could arguably only say that in an universe where `val + val` is the only possible operation, and even then, that's not really correct because the utility of the function is hardcoded (meaning that if we were to hypothetically introduce an axiomatic operation, the internal consistence of this new algebra would implode). In a more useful algebra in a regular universe, the mapping must hold for any valid operation for that type. So a functor for the `number` type ought to look more like something like `Number.prototype.map = function(f) {return f(this)}` (i.e. the mapping contract holds for addition, subtraction, and all other algebraic operations that are valid on numbers contained within `f`)
There are also practical technical things the article glossed over: Array.prototype.map is not monadic. The signature of the callback is `(T, number, Array<T>) => U`, which is most certainly not unary (and for that matter, using JS to illustrate FP is fundamentally problematic since JS isn't side-effect-free to begin with). If you think that's nitpicky, one fundamental thing with FP is that composition relies heavily on algebras not breaking on corner cases. This is why, for example, fantasy-land specifies a different method name for `map` (called `fantasy-land/map`); because `map` is already taken by Array and it breaks some composition patterns (notoriously, `[1,2,3].map(parseInt)`)
> Array.prototype.map is not monadic. The signature of the callback is `(T, number, Array<T>) => U`, which is most certainly not unary (and for that matter, using JS to illustrate FP is fundamentally problematic since JS isn't side-effect-free to begin with).
The unspoken understanding in the OP is that we're only using .map() in the single-argument form. The author makes it clear that only a function with a single argument counts for their definition, and I feel there's also an implicit understanding that that function has to be pure.
The fact that JavaScript technically lets you break both of these assumptions is entirely beside the point. For the sake of teaching, this idealized case is carved out for the example, and I for one had no misconceptions resulting from the relevant quirks of JS. We aren't writing a bullet-proof type system here, we're learning about concepts.
Perhaps I'm getting a different reading from the article than you, but as someone who's gone in and out of this rabbit hole, I found that the author was making some pretty stretchy claims. For example, he says "It may also seem like every monad that is needed already exists. Some common ones are" and proceeds to name Arrays and Promises, neither of which can be used in functional composition beyond the very basic `foo.map(f)` (and may break even then, as per my trivial example above!)
It's fine to try to use a non-functional language to try to explain functional concepts to those who are familiar w/ JS but not FP, but also keep in mind that you may be misunderstanding unknown unknown nuances because of the misappropriation of one domain (JS) to explain another (FP). You yourself are an example of someone who seemed to be about to take a mischaracterized technicality at face value before an avalanche of people started pointing out issues. How do I know to what extent you or someone else understands the implications of functions not always being endofunctors, Arrays not actually being monadic, or why map vs fantasy-land/map matters?
There's a real cost when people come out of reading articles thinking they know more FP than they actually do. This exact discussion about strictness already had implications to the design of Javascript itself: the algebraic consistency argument was brought up while Promises were being specified, but it got dismissed and we ended up with non-monadic promises (and shitshows festered all over the place as a result, e.g. rxjs had to special case them, and we have stuff like fluture.js because why not have multiple future types). The Fantasy Land project itself was created out of spite of a dismissive comment in the promises discussion calling algebraic consistency "fantasy land". On another occasion, one of the React core team members went on twitter at one point saying react hooks are pure (and don't even get me started on algebraic effects). The amount of misunderstanding surrounding FP - even among JS engineers at FAANG - is frankly scary and "loose-is-fine" mentality seeping into the design of widely used APIs is not exactly ideal.
Like, it's fun to communicate in technical jargon -- and personally I'm quite proud of the vocabulary I have built up over time -- but you are totally correct in that it serves as a gatekeeper for an in-group to retain its dominance over a given field. There is a lot to be said for effective communication using a simple, base language and reserving obtuse technical terms for areas where one needs to be very specific.
There's another point to be made for not inventing new technical terms when existing ones apply. The amount of overlapping terminology in this field is infuriating to me.
This is true across all disciplines...
I don't agree that having a domain jargon that is technical and concise is "gatekeeping" for functional programming. If you are a frontend developer you need to know what the DOM is. If you are a Haskell programmer you need to know what a monad is. The fact that you don't get the Haskell jargon "for free" coming from other programming disciplines doesn't mean that it's "gated", it just means you need to learn. And there are plentiful resources to help you with that, countless "how to understand monads" articles and so on. In my experience, the Haskell community is perhaps the single most welcoming and helpful programming community. There's even a handy guide with big, friendly drawings.
It's like, effing pick one! And if you have to have multiple why do they have to overlap with other completely different things? When I first read about a 'map' in this context I was very confused.
You also see this a lot comparing Microsoft environments to everyone else. Reading microsoft docs in the late 90s (which is where I first learned a lot of these concepts) you learn one set of vocabulary, and then in the _nix and webdev worlds you learn a whole different set. Take 'databinding', for example... I have not once heard this term used discussing shadow DOM stuff like React or Vue, yet databinding is exactly one of the services they provide. But no, they have to call it something different, making a lot of prior-art type research much more difficult than it needs to be. Perhaps it is part of the reason why the webdev world seems so intent on pointlessly repeating history. It hampers discussion and contributes to the conceptual isolation and tribalism that seems so common in this field.
(And in the perl example, yes I know it's short for hashtable and that this is because this dictionary-like thing is exactly that, but I think that from an end-user's point of view it would be best if all these different terms were unified)
With that said I may have gone on a bit of a rant here and made some generalizations, and I don't feel good about that aspect, so I apologize.
I think a big part of it is difference in definitions. There's the mathematician's monad, which is pure and abstract and obeys all these laws. And then there's the engineer's monad: an interface you can map, ap, and flatmap over. People get so hung up over "algebraic purity" they forget why they were invented/co-opted for software in the first place: to solve the problem of applying pure functions to side-effecty operations.
> A monad is a wrapper. Anyone who tells you otherwise is being obtuse.
I'd say reading the Bible, or any other deep philosophical/spiritual text in a translation is almost an utter waste of time (unless that actually helps you psychologically, then it is not), if not harmful.
The original words and phrasing with all their possible meanings make a huge lot more sense than specific translations.
Something that sounds banal or weird can actually mean something entirely different and deep once you carefully analyze the original words.
It is, however, important to remember Latin is not the original for the Bibile. But it still has a lot of what has been lost in many other translations.
A functor has two pieces: a pure unary function from types to types, and a pure unary function from functions to functions. The article doesn't talk about the function on types; it doesn't even talk about the function on functions. Its first example of a functor is the function `(num) => "" + num`, which isn't a functor. They map values of Integer to values of String, but they do not map any type to some type, nor do they map any function to some function. Neither part of a functor is present nor nearby.
As an example, for every type T, there is a (non-generic!) type of lists with elements of type T. The non-generic part is really, really important, and is probably a big source of confusion. When we define, say, `class List<T>`, we're defining a whole family of independent types, which we might concretely name List__Integer, List__String, and so on. The List<T> notation is a way of getting that specific type without knowing what its name is. By abuse of notation, we (programmers, not category theorists) talk about List<T> as though that were the name of the type. Theorists separate the two notions, and consider `List` to be an actual function from types T to types List__T, whatever that type actually is.
Most languages that let you define a family of types don't let you refer to the type function on its own. Java (say) never lets you refer to the List function on its own; the name List refers to some other shameful and unrelated concrete, non-generic type. When your language does let you speak about the type function itself, and pass it around to other things, we say that it has "higher-order types". (Just as a language that lets you speak of and pass around a function `factorial` without invoking it has "higher-order functions"; notwithstanding closures, that's what "higher-order" means. [0])
Just having a type function is not enough to have a functor. You also need a function that takes transformations between two types, T and S, to transformations between whatever types the type function sends them to. (For List, we said they're called List__T and List__S, but we can always refer to them indirectly by saying "whatever List maps T to", which is generally written F<T> for any type function F.)
Because of the abuse of notation, we collectively "forget" that `List<T>` defines a function from types to types, and pretend that a functor is just defined by what it does to functions from T to S. But most of the point of functors in functional design is that you can pass around the type-function part, `List`, with the knowledge that it describes a mappable type. If you don't pass around type functions, the concept of a functor will be useless to you.
Though in my experience even the "flash cards" are hard to find on the internet.
There's some magic to these words, but that magic is in how they're used to create new software, real things you can do with them that are easier to talk about when you've got single words for the concepts instead of vague descriptions.
People in Haskell do things like having concatenating to an array be the same syntax as executing two statements sequentially. That's sort of weird, and probably useless, but the whole idea that two sequential statements are basically a monadic operation over the state of your computer, and maybe over the entire world was a new idea in the 90s and it captured something in the formal domain that we hadn't really captured as well before I believe.
edit: I'm not trying to convince you that monads are important or even useful in general, I hope it doesn't come across that way. My favourite programming languages don't have monads as a fundamental concept, Haskell fell from my list a couple years ago. It's an interesting way of thinking about types and computing and I think that makes it more interesting than just a bunch of dense definitions for mysterious looking names.
And guess what another name for a unary functions is... 'monadic'.
Functors capture a particular pattern of "pipelining": a series of operations A -> B, B -> C, etc. can be uniformly assembled in the context of any arbitrary functor F, ultimately giving a unary pipeline `F A -> F C`. (I won't detail what this means completely; I'm going for a gut instinct in the following bit.)
But what if you have a binary function, (A1, A2) -> B? Functors only let you assemble unary operators; there's no provision for taking the outputs of two pipelines and weaving them together. Applicatives (or, "monoidal functors") give you an additional operator that let you turn a pair `(F A1, F A2)` into a contextual pair `F (A1, A2)`, which can then be fed to a unary pipeline. (In terms of pipe shapes, it's a Y-bend.)
Monads extend this in a less interesting way, but in the sense of "monadic" as "unary", functors are actually more monadic than monads!
That's only Haskell. The other FP languages have sane communities.
A monoid is something where you take two things and multiply them to get one thing. 2 x 3 = 6
In a monad, you take a doubly-nested thing and "multiply" and get a singly-nested thing: [[a,b],[c]] => [a,b,c]
The monoid laws say that, though you can multiply in different ways, it doesn't matter what order you do it, the end result is the same: (2 x 3) x 4 = 2 x (3 x 4)
The monad laws say the same thing: the order you do the "un-nesting" doesn't matter:
Inner-most first:
[ [[a,b],[c]], [[d]] ] => [ [a,b,c], [d] ] => [a,b,c,d]
Outer-most first:
[ [[a,b],[c]], [[d]] ] => [ [a,b],[c], [d] ] => [a,b,c,d]
-----If you take the definition of a monoid, which has stuff like
M is a type
multiply : M x M -> M (multiplies two elements)
what it means to do it "in the category of endofunctors" is it changes into M is an endofunctor, a is any type, Ma is M applied to a
multiply : M(Ma) -> Ma ("multiplies" doubly-nested element)
and when you do these changes for the whole definition of a monoid, what you get is exactly the definition of a monad.Here is a correct explanation: https://stackoverflow.com/a/3870310
That's algebra tho, which is very relevant to functional programming (monoids capture the essence of composition) in general, but not the right monoids in category theory.
https://www.slideshare.net/ScottWlaschin/railway-oriented-pr...
https://fsharpforfunandprofit.com/posts/recipe-part2/ for a text version
https://fsharpforfunandprofit.com/rop/ for the "hub" that discusses how this isn't really a monad tutorial but hints at how you can go deeper - and if you read this before you read the OP you can see how the meta-puzzle pieces fit together!
At the highest level, this helped me see that monads are really just Level 2 of "things that help you glue things together that weren't meant to be glued together (particularly if those things emit changes to some external state.)" And that's exactly what the railway/error-handling analogy brilliantly shows. You've probably written almost-monadic things yourself, you just don't know it!
It's actually a satirical joke[1] that people started taking way too seriously. Honestly, imho people should never use this line when explaining monads. It's like saying 'C is a purely functional programming language!' because Conal Elliott, around the same time, wrote[2] a parodic blog post making fun of purely functional programming zealots.
[1] https://web.archive.org/web/20210824072932/https://james-iry...
[2] http://conal.net/blog/posts/the-c-language-is-purely-functio...
The phrase that forms the title of this post is very close to what (CT giant) Saunders Mac Lane wrote, quite seriously. In fact it's missing the word "just"! Iry was inspired by Mac Lane, but you seem to have got the wrong end of the stick on the actual status of these words.
See, for example, https://stackoverflow.com/a/3870310/14768587
In this context, it's quite obvious that I am correct. Programmers around the world wouldn't have been perplexed for a decade because of a labyrinthine quote from Mac Lane's Categories for the Working Mathematician.
2. no side effects
And you get most of the benefit of FP in a way that everyone can understand and can use any language.
You could argue that because of this system the language itself is pure and without side effects and without mutation.
Note that the effect of this system is exactly the same as a language that does have side effects. They are functionally identical. The nicety of Haskell's purity comes from how the monads allow you to organize your code.
By the way, not sure if this is controversial but JavaScript's I/O system is a lot like the I/O monad. I/O doesn't really get executed immediately, and you can't directly operate on the results of I/O. The runtime executes the I/O after all JavaScript's been executed, and you use callbacks to tell the runtime to do whenever the I/O data returns.
Of course JavaScript does allow for mutation, so it's not pure in that sense.
https://en.m.wikipedia.org/wiki/Monad_(functional_programmin...
Namely, I’m wondering what kind of thing is even capable of being a monoid and an endofunctor at the same time. Mathematically, a monoid is a set (or collection to be more general) closed under a binary operator (the monoidal product) and with a distinguished identity element. An endofunctor is a mapping from a category to itself, which entails a mapping of each object as well as a mapping of each morphism. So I’m not even sure how to parse the phrase “monoid in the category of endofunctors” because the data required to describe these two things seems completely different.
In particular, usually a monoid is defined as a single object category (sometimes a "monoid object" is defined inside a category, but that's a different presentation). The usual multiple objects of an algebraic monoid correspond to different arrows/morphisms within a monoid.
So for example, while the usual algebraic presentation of a monoid would say the integers form a monoid with an identity element `zero` and normal integer addition forming the monoidal operator, the categorical definition says instead that the monoid is the category that consists of only one element Unit and the morphisms (x => x + 0), (x => x + 1), (x => x + 2), etc. We have an identity morphism (x => x + 0), which when composed with any other morphism does not change it (x => x + 2 composed with x => x + 0 still is just x => x + 2). This is a common pattern in category theory: everything is reduced to composition.
So that's a categorical monoid, just a single object with a lot of morphisms and an identity morphism. We can back out the usual algebraic definition by associating with each morphism the "element within" (i.e. associating (x => x + c) with c), but it represents a different way of thinking.
We can also talk about a monoid object in a larger category in much the same way.
Hence now that we can talk of a monoid as a single object, we can then say that an endofunctor is a monoid (given the proper mappings on an endofunctor, i.e. natural transformations).
Indeed that is one way of viewing a monoid. However, the most basic categorical definition of a monoid (and the first one usually introduced in a category theory textbook) views it as a category with only one object, where all the "interesting stuff" happens with the morphisms. A monoidal category and monoid objects are a restatement of that idea in a larger category.
Given a functor m of Hask, we define a squiggly arrow ~>, where a ~> b is a -> m b. If these ~> are the arrows in some category (which we call the Kleisli category for m), then we call m a monad. Here id :: a ~> a in that category is what we call return :: a -> m a, and the composition (.) :: (b ~> c) -> (a ~> b) -> (a ~> c) in that category is used to create bind :: m a -> (a -> m b) -> m b, where bind x f = (.) f (const x) (return ()), where (.) is the squiggly arrow (.) we just mentioned. Bind is what's spelled >>= in Haskell, and is what's behind the "x <- f" do-notation.
The problem in this thread is not that monads are controversial or poorly understood. The problem is that there is a strong selection effect: the thread is populated by people for whom the topic of monads is relatively new, and who think that this discussion is worth having in this context. People who are "productive" with monads already know exactly what the structure is (it's not complicated) and they're unlikely to want to enter this discussion. They just have better things to do than engage with the misconceptions of "learners" on the Internet.
HN in general suffers from posters who write confidently about things they don't fully understand. This tends to drive genuinely competent people away from the site. It affects politics as well as tech discussions.
The problem isn't monads, it's the denizens of HN.
Like many, I'm still learning a lot of this - especially the formal terminology and the distinctions between the mathematical and computational variances of these ideas.
It can be tough to push past the more intense and techincal jargon and I enjoy writing about these ideas to document my learnings for myself and to try and make it more accessible to others.
I'm happy some found it useful and for the discussion here where people can help correct and inform parts that aren't as sound.
E.g. Arrays are monads under concatenation. So why people then say easily "Option type is monad" without stating under which operation? I assume Option is monad under "all" and "any" function, but not sure.
1. A type constructor M of a single argument 2. A function of type a -> M a 3. A function of type M (M a) -> M a
subject to the monad laws. So the 'array monad' is the triple (Array, \x -> [x], Array.concat) and the 'option monad' is the triple (Option, \x -> Some(x), \x -> match x | Some(o) => o; None => None). Saying a type 'is' a monad is imprecise but just means it has an associated monad instance. I've never seen a type with multiple monad instances but I don't know if there could be one.
There can, it's just like there can two monoid structures on the same set. In fact if you have an example of a set S which has two monoid structures, you have an example of a functor with two monad structures: _ × S. join multiplies the two elements of S, so you get a different monad structure for every monoid structure on S.
Btw, I think you got a mistake there, in the third part of Option should be "Some(Some(o)) => Some(o), Some(None) => None, None => None", otherwise o can be not an Option at all.
let join_option oo =
match oo with
| Some(o) -> o
| None -> None [] => []
[[]] => []
[[a]] => [a]The next header is: What's in a Monoid.
If you are going to toss funky sounding words around then please get the basics right.
A thing and what's in a thing are rather different things.
Not saying it's not out there or useful - just saying that after 20 years I'm yet to come across it once.
Just because you don't see FP out in the wild being conspicuous, doesn't mean it's not there ;-)
- WhatsApp: famous for being written in Erlang, a functional programming language, and processing more messages a day than the entire global SMS network with a team of 50 backend engineers
- Discord: handling extreme amounts of chat/call traffic using Elixir, another functional programming language based on the same tech as Erlang
- Telephones: telephone switches from Ericsson (and in fact, internet switches from Cisco) use Erlang
- Docker: core virtualization component for macOS (hyperkit) written in OCaml
- Amazon EC2: another core virtualization component of all computes, parts of the Xen hypervisor, written in OCaml
Here's a list of companies using Haskell, with similar links to other functional languages: https://github.com/erkmos/haskell-companies. It includes names like Facebook, Tesla, Klarna, Target and Kaspersky.
Not to mention the FP paradigms used in Python, C++ and other languages. In fact, if you've never come across FP "in the wild doing something" then I suspect you're living very much off-grid.
Begs the question has a specific meaning.
From the HN guidelines:
- Please respond to the strongest plausible interpretation of what someone says, not a weaker one that's easier to criticize. Assume good faith.
- Please don't post shallow dismissals, especially of other people's work. A good critical comment teaches us something.
- Eschew flamebait. Avoid unrelated controversies and generic tangents.