359 points · by zdw · 5y ago · 248 comments
> ...too often act like ivory towers...
I 100% agree with this. The Haskell community as a whole and various tutorials etc., aren't optimised for a new comer.
For instance, you don't see a "stand up a web app in Haskell in 10 minutes" tutorials. Historically it may have worked in Haskell's favour to slowly induct learners, but in this age where languages are fighting for mind space I don't agree that's a good approach anymore.
Simon Peyton Jones (SPJ), an earliest and a famous champion of Haskell coined the phrase "avoid success at all cost" in a certain context which may have had some role in making Haskell seem Ivory Towerish.
A language, like any living being, needs to adopt to survive and thrive. It's unfortunate to see Haskell remain a niche language even after close to 3 decades.
> and that simply is not how my brain is wired.
This, however, I disagree with. I mean in a general sense, not specific to how your brain is wired. It all depends on the first couple of language that one learns and how they are learnt and taught. 10-15 years ago people would find it hard to grok Python's functional concepts. But as it began to be taught as the first language in universities and those graduates join the working population you see how it's super natural for them to grok Python.
That must be the reason why Edsger W Dijksta once stated [0]:
> "It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration."
... and ...
> "The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense."
... and ..
> "APL is a mistake, carried through to perfection. It is the language of the future for the programming techniques of the past: it creates a new generation of coding bums."
I must be one of those mentally mutilated programmers with no hope of regeneration :)
---
[0]: https://www.cs.scranton.edu/~mccloske/dijkstra_quotes.html
Elitism and gatekeeping do precisely nothing to help people solve problems with code.
I include myself. It has been a definite struggle to onboard functional concepts and solve problems in a functional style. Just doesn’t come naturally.
I'd like to argue on how reasonably simple is simple enough. If I need a carpenter to build a stairs I'm my house, I would expect a good carpenter to know and use all the tools appropriate, no matter how complex. Of course, most things are doable with just a hatchet just fine, but I d expect a professional to choose a hatchet because it's better, not because they never bothered to learn proper tools.
So whenever a language puts "easy to learn" as their main feature, I see it as a guide "how to build stairs with just a hatchet".
There's now the IHP framework that allows you to build haskell web apps in like 10 minutes. If you're curious, check it out: https://www.youtube.com/watch?v=UbDtS_mUMpI It's been called "Haskell on Rails", and for good reason.
This phrase is often misunderstood, it's "avoid, success at all costs", not "avoid success, at all costs". In other words, don't optimise for mass market adoption at the expense of everything else. Languages that have arguably done so, have ended up as extremely complex and ridden with corner cases.
It's easy to follow a rule too far and end up way overcorrecting the original problem. What I like is that both meanings balance each other :)
Some popular mass-market friendly deliverables don't cost very much at all, avoid them and you're definitely avoiding success at all costs, but with both meanings at once this time.
As I understand it, the core Haskell folks don't especially care about Haskell's (admittedly limited) real-world usage. Or, if you prefer: real-world usage is a side-effect, not a value.
Yes, there is a lot of research being done on Haskell, but a lot of the research is centered on areas that more or less directly contribute to typical real-world usage. Consider the recent introduction of linear types for example: They're both exciting from a type theoretic perspective, but could also improve some real-world scenarios (even though at this point linear types are still quite new, so there's not a lot of examples out there).
"avoid success at all costs" is usually meant to be parsed as "avoid [success at all costs]" i.e. don't compromise the language just to make it more popular.
> This, however, I disagree with.
I think it might well be correct, actually. I think that it might be the difference between abstract and concrete thinkers on that standard personality test. Abstract thinkers will find that Haskell makes more sense; concrete thinkers will find that C makes more sense.
First of all, I completely understand where you're coming from.
But the fact that Haskell embraces computer science, unlike most other programming language communities, is what attracts me to it the most. I can geek out about the mathematics that leads to simpler, safer software with like-minded people. I am always learning from Haskellers more than from any other programmers.
But it does take a lot of learning and unlearning to become a fluent functional programmer. This isn't because functional programming is more complicated than other paradigms (au contraire), it's because schools and universities have been mostly teaching OOP for the past 2-3 decades—unfortunately. As a result, most programmers have such a big gap in their knowledge that it can feel too daunting to dive in.
We could definitely do a better job teaching the theory and explaining how it's useful. That would be better for everyone: better for curious minds who want to expand their programming skills, and better for me because I'd have more company to discuss it with.
Just no.
The reason Haskell is so complicated to become fluent in has nothing to do with the inherent complexity of functional programming. The Haskell community is just in love with complexe abstraction for the sake of abstraction, extremely terse and hard to understand syntax (see for example the obsession with introducing convoluted operators) and generally favour hard to understand style like point free where pipes are a lot easier to follow. The Haskell community is full of people who are here to geek out rather than produce software. Haskell is what happen when you let one upmanship leads your language design.
Meanwhile, you can learn SML, F# and Ocaml in a couple days, gradually enjoy the functionality they have to offer and benefit for a nice community. I really don't understand why anyone would choose Haskell.
No they don't. Every Haskeller I know (myself included) acknowledges that sometimes point free style is better, and sometimes it isn't. None of them would unilaterally declare it better, and most generally avoid it except in very simple situations.
> The Haskell community is full of people who are here to geek out rather than produce software.
The Haskell community is full of people who are here to geek out about the best ways to produce software. This means they embrace tools like mathematics, and are generally extra thoughtful about structuring programs in principled ways. It's a wonderful community of people who care about the details of their craft and treat it like a skill to be honed over time. I have a lot of respect for that.
If I could rant for a moment: I'm really sick of spending many years of my life investing in myself and my ability to produce software with the best tools humanity has to offer, only to have these people in Hacker News tell me I'm just doing mental masturbation when it seems like they don't even understand what they're criticizing.
\x -> h $ g $ f x
At a certain point you realise that in many cases seeing the `x` is not just useless but needless visual noise. The following is identical and more readable once you've internalised composition:
h . g . f
And this extends to a cute trick in which, if you need to explicitly provide that data to begin with, you can do this:
h . g . f $ x
I'm now working with Haskell having previously come from PHP and JS/TS. Composition is more readable, it's just harder to get started with because it's different to what you're used to.
As for the "geek out" comment, of course, I enjoy programming for the intellectual sake of it. I'm not product-driven. Don't make the mistake of thinking everyone's the same as you, nor that of thinking there aren't benefits to being so intellectually-motivated. I don't know if it's intentional but your comment comes across as rather self-righteous.
In particular, most algorithms research and papers are expressed in imperative pseudo-code, as that is, in fact, much easier for humans to intuitively reason about than complex category theoretical concepts.
We're not talking about any complex category theoretical concepts here. Functors, for example, are one of the first ideas one would learn in a category theory course. Likely even in the first lecture.
Even the most advanced functional programs use only the most basic categorical constructs.
And when you say "imperative pseudo-code", you've already conjured an implicit monad involving state, I/O, etc. Functional programming just teaches us that it's not the only one—and there are simpler ones that may be more appropriate for the given situation.
I’ve used functors and monads to solve tons of issues and have literally no clue about the theory behind them.
That's completely fine. Haskell is not a single community. There are two big camps that often interact with each other, the academic and the industrial. Keep in mind the origin of Haskell is academic and it's original purpose is to test and implement ideas from Programming Language Theory. That is still there and will continue. GHC optimizes for letting people experiment with language extensions. Industrial interest didn't start to grow until somewhere around 2008-2012. It is a small community and will likely remain so.
I am a big Haskell user myself. There are many theoretical things I don't understand or need to touch, but I appreciate their contributions to the language and the community. I do agree that Haskell has lots of room to improve on tutorials for non-academics. Maybe I will get inspired to write somethings.
It's completely fine if you don't want to use it. However, you may find Haskell users' enthusiasm for the language insufferable, hehe. I do hope anyone who chooses to interact with the Haskell community finds us welcoming.
You need to give the reader some real world example. A concept dangles in brain without connects to other things won't live too long. You brain is likely to `optimize it out` because it is unused.
For balance, here's another common opinion about tutorials: http://dev.stephendiehl.com/hask/#eightfold-path-to-monad-sa...
> [...]
> Read the monad definitions.
> Use monads in real code.
> Don’t write monad-analogy tutorials.
In the end, the two opinions about learning monads coexist, and people have done fine following either way.
With a ‘theoretical’ description, like a BNF grammar or a Unix man page listing every possible option the program accepts, this is immediately obvious. Haskell’s focus on ‘theory’ follows the same philosophy.
In any case, all knowledge needs to be elevated to some level of theory because a correct theory guarantees the repetition of correct application.
This post helps on some of these points, like explaining that e.g. functors are not always containers.
I’d love to see someone try taking it further: just hashing out lots and lots of substantially different examples, showing how they are similar to each other, and progressing into higher level transformations, before finally showing the definition of a functor, and how it maps to each of those cases. Forget monads. Can we just start with functors and see how far we get with that?
I think this is how a lot of people learn math and programming anyway. Build theory out of intuition.
Post-secondary math classes were actually amazing to cultivate the habit of persisting through long periods of feeling like a complete idiot. But I have to wonder what the same content would have been like had it been example-driven.
It reminds me of learning a language through exposure to endless examples and internalizing rules without being explicitly taught them, versus deliberately memorizing the grammar rules of a foreign language and then applying the rules to specific examples.
Ugh. So much this.
I've had so much difficulty grokking mathematical concepts and procedures in my life. In high school, I fell behind so hard.
Algebra I was doable, and while learning Geometry I felt like I already knew everything about the subject. I never studied and the admins concluded that I must be cheating, given my performance in other courses.
I concluded that in order to learn these things, I had to have "something to do with it". So to speak, some relatable examples to which I could apply the concepts in order to internalize the rules. This strikes me as the source of the never-ending choruses that are echoing still through so many study halls. ringing out, "WHEN ARE WE GOING TO NEED THIS???"
If feels so good when the concepts click, it's like learning you had a superpower. Suddenly, the baroque, mysterious walls of lines instantly resolve into such crisp focus, it truly is an amazing epiphany, Ah-Ha!
I feel like I could have really enjoyed the discipline, but I never achieved this feat in my educational career. I had problems that dramatically redirected the course of my life. This is probably why computers appealed to me so much, because of the direct cause-and-effect nature of interfacing with them. The Hacker Manifesto comes to mind, but I digress.
I have Narcolepsy Type II and probably ADHD (as you may infer from my comment history) and let me tell you...
Often when presented with a definition it's easy to get fixed with examples that are too specific and then to conflate the definition with something a bit stronger.
How I actually learned the math was by examples and easy exercises, not understanding proofs.
class Functor f where
flip fmap :: f a -> (a -> b) -> f b
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
Sorry, that's not doing much for me! I am now going to look for a tutorial on Monads that's written in, say, Python, so at least I don't have to learn an abstract new language alongside the abstract new concept.It probably won’t be very helpful. The definition of a monad is 90% in the types.
People use Haskell to talk about monads for two reasons:
1. Its type system is expressive enough to represent them (parametric polymorphism and higher-kinded types)
2. It’s one of a very small number of languages that doesn’t let users wiggle their way around needing some kind of principled effect system, so you really can’t get away without monads. Only in such an environment can the social pressure to take shortcuts be overcome, forcing people to structure their code carefully enough that the rich concept of monads isn’t reduced to a few occasionally used and probably incorrectly implemented corner cases like optional values and maybe futures.
There seems to be a disproportionate amount of tutorials about monads. Not being able to provide sufficient amount of examples in other languages makes monads seem quite less useful. Maybe next article to write is “why should you learn about monads”.
"If you don't need IO sequencing, or purity because your language doesn't care about purity, or the list implementation's nondeterminism because that's a parlor trick, or STM because your ecosystem doesn't use it... there's not much point to worrying about it. Monad implementations in languages other than Haskell fail to take off because there generally isn't even a single thing that is improved by working with it through a monad interface, let alone a family of such things."
"[...]It's definitely an interesting idea, and if you are a curious programmer, it's worth learning about this particular interface and what it can do. But it's not something you generally directly take back to your language"Nonetheless, these are all monads, and learning specific monads helps in lots of other languages. Optionals are nice in Java. Arrays in Lisps. Error handling in Scala. But the "universality" of monads escapes these languages. I would kill for better monadic error handling in Go, but conversely I would have little use for monadic I/O or futures.
The critical mental step is seeing the commonality in all of these, which is really only possible in languages at that level of type sophistication. And necessary in Haskell where the particular combination of purity, laziness, and HKTs means monads are the only way decent way to do most of these. Once you see that commonality you can develop tools - patterns of mental reasoning about code and idioms for writing code - you can also use when dealing with the specific monads or nearly-monads in other languages. But you can't show that property in examples in a single other languages, and it's difficult to show how some deep structure is shared in examples spanning five languages.
If your type system can't express them then you lose most of the advantages and they're pretty pointless.
The definition of a monad, as it relates to programming, emerges when you realize that an Option type, a Result/Either type, a List type, and a bunch of other non-container types all have the equivalent of a `flat_map` function. Write out a few mathematical rules for how a well-behaved implementation should compose and you have a Monad and its rules.
This is why another approach to learning monads that isn't focused on the theory introduces it as a design pattern instead. I find this to be great for intuition but horrible for understanding personally, having used both approaches to teach people about Monads IRL.
Nevertheless language ecosystems outside Haskell, scala and F# don't recognise this as a general programming pattern, although given the current direction towards FP in the JavaScript and rust communities I think it's a matter of time.
At first glance monads seem less useful in languages with builtin mutable state, and freely allowing side effects. However, if you’re writing somewhat more high-level domain specific code there are plenty of concepts that can be modeled using functors and monads very elegantly.
Parser combinators, distributed data fetching, reactive data streams, composable tree traversals, etc
I use them all the time in for TypeScript.
To put that a bit differently: Haskell is a strait-jacket. In the name of purity and laziness, it takes away a lot of things that other languages give you. Monads are the hoop that is left, which you have to jump through in order to be able to do what you can do in a more straightforward way in other languages.
I'm saying this in a negative way precisely because you said it in a positive way.
But which is it really? Is it a positive or a negative? Depends on who you are and what you're doing. Depends on how much your program is improved by not having the wiggle room, and how much of the time you're doing what is easier to do in other languages.
("Easier" might not be the right word. Do notation isn't that bad of a notation for expressing sequencing in. It's a bit cumbersome, but it's not terrible - it's not like building the sequence monads by hand. It's still producing them under the hood, though. Whether that's a problem depends on how badly you need speed, how much pressure the garbage collector is under, how much of the program needs to be sequential, and so on.)
A definition like:
bind f (x:xs) = f(x)
would fit this type signature, but would very much not be a monad.What makes a monad a monad is that it is a functor (so a special parametrized type of sorts) with
- a function to wrap a single value (wrap :: a -> M a)
- a function that can flatten nested versions (flatten :: M M a -> M a)
- such that wrapping twice and flattening is the same as wrapping once
- such that when flattening a triply nested structure it doesn't matter which level you flatten first.
And of course it also needs to satisfy the functor axioms, which are also frequently overlooked, though they're not too difficult they just mean that 'fmap' needs to play nice with identity functions and function composition.
And Haskell in particular suffers quite a bit from the fact that currying is a first class concept, while in category theory this is reserved for a rather special class of categories. This means that using functors in combination with functions of multiple arguments suddenly requires you to think about how to evaluate a tree of functions on a tree of values, where in most other languages you'd end up with a tree of tuples at worst. Granted you can do more if you solve those problems, but it requires you to think about concepts that even category theorists consider pretty 'out there'.
I agree with you entirely that the Haskell syntax is probably one of the biggest issues with monads being approachable.
I've tried to read up on some Haskell basics, but the main issue is I don't have any real incentive to use Haskell, I have other hobbies that are more tempting, so I forget pretty quick.
The Java-ish version of the Functor interface for instance was quite readable to me, ugly or not.
Haskell folks love arrows and one letter variable names.
I don't know why, I guess it's the algebra background of most Haskell folks.
When I wrote some things in Haskell, I tried to use full words for function names and variable names, but it felt I am the only one. People just love to name stuff `a` `b` `m` `f` `k`
interface Functor {
<T, U> Self<U> fmap(Self<T>, Function<T, U>);
}
which is just torture. What would it look like in your ideal syntax? interface Functor {
<Source, Target> Self<Target> fmap(Self<Source>, Function<Source, Target>);
}
Same code, but you get an additional hint of what's going on. # milk_cows :: Person -> Tired Person
def milk_cows(person):
...
person["tired"] = True
return person
# feed_pigs :: Person -> Tired Person
def feed_pigs(person):
...
person["tired"] = True
return person
# birthday :: Person -> Person
def birthday(person):
person["age"] += 1
return person
# willy :: Person
willy = {"age": 32, "tired": False}
# fmap and >>=
print(milk_cows(birthday(feed_pigs(willy))))
In Haskell there would be a 'Tired a' type with a Monad instance to express the tiredness property and a Functor instance to apply functions to it with no impact on or knowledge of tiredness, e.g. aging.Would you agree that introducing particular interface is gonna show interface definition in question?
What should follow (just like in Java) is few examples of actual implementations and how they fit into that interface.
for example, if "f" is "list of" and a is "integer" and b is "string", then flip fmap would take as input a list of integer, and a function from integer to string, and produce a list of string.
If you've done some topology: [or, maybe a is a particular topological space and b is another topological space, and f is "the fundamental group of", then given an element of the fundamental group of a, and a function from the topological space a to the topological space b, it will give you a corresponding element of the fundamental group of b.]
a and b are both types of things, f takes in a type, and outputs another type. so, a and f a are both types (usually different types). the thing is that f doesn't just let you make a type from another type, it also lets you translate a function from the type a to the type b, to a function from the type f a to the type f b.
It's easy if you first learn about Haskell notation and type classes, which pretty much every online tutorial covers. What you quoted isn't arcane, you're just unfamiliar with it (just like my granma would find C-like syntax illegible: she just wouldn't know anything about it).
However, I can't help but feel that the author and I have some common flaws.
The first being verbosity. I often notice the same thing in my own writing: I will see a well-written paragraph and think "this is good stuff" and then wonder "but what purpose does it serve here?" Stuff like dedicating 5 paragraphs to discussing whether Functor should be a noun (I get the point, but that's a lot of words to make it), or a paragraph with caveats about how Haskell does name resolution.
The second being that we both seem to have fallen victim to the monad tutorial fallacy (https://byorgey.wordpress.com/2009/01/12/abstraction-intuiti...). But I'm not 100% sure about this one. I don't think it's wrong to call monads interfaces in the same way that it's wrong to call them burritos. However, our framework of thinking does seem to align with what that author refers to as fallacious.
Still was a good enough read that I felt the need to comment partway through :)
(This isn’t an entirely new kind of concept in programming, either; see “patterns”.)
which to me is an interesting debate given Haskell's emphasis on strong interfaces strictly enforced.
We seem to be converging on a world where we agree that declaring and enforcing types is very important, yet also that it's the structure of the type, not its name, that is most critical. At some point, with sufficiently advanced type inference, do you end up in a world that looks like a lot like fully dynamic languages, where the actual declaration of the type is purely optional?
The paragraph starting with "I am aware of the notorious effect" directly addresses this, do you disagree with it?
Also calling it an interface isn't an analogy.
I suppose my answer should be "yes," but let me try to explain my convoluted reasoning:
Understanding monads simply in terms of interfaces is what I think is the silver bullet to comprehending them. It's what helped me "get" them. So they are my "burrito."
> Also calling it an interface isn't an analogy.
I agree, I apologize if I came across this way.
I strongly agree with valenterry's comment[1] here, that post gives is an approximate definition of functors, even omitting the functor law. In particular, it is explaining what an endofunctor is (in the context of FP, you mostly deal with one category anyway). Furthermore, even in Haskell, there is no such thing as the category of Haskell types[0] (because of things like divergence and partiality).
For the curious, I've recommended Program Design By Calculation[2] to a number of people to show how category theory can be used as a powerful tool to reason about programs in an FP context while not compromising on the mathematics (the target audience is undergrad CS majors).
EDIT: In particular, I have a bit of issue with this sentence after stating the signature of fmap, since it does not reference lawfulness.
> This is the full definition. There is no additional hidden machinery that Haskell is somehow automatically invoking when you "use a Functor".
[0] http://math.andrej.com/2016/08/06/hask-is-not-a-category/
> A function is a relation for which each value from the set the first components of the ordered pairs is associated with exactly one value from the set of second components of the ordered pair.
Cool, I have no idea what the fuck this means and how it is useful to me.
Oh wait, I use them every day.
> Oh wait, I use them every day.
Do you really? Do the `functions` you use even fit the above definition?
I bet you can think of infinite number of functions (bool -> bool). The above definition admits only 4 such functions.
Divergence and partiality can easily be modeled by the category of complete partial orders and Scott-continuous maps. This is what you learn in, e.g., a course on domain theory and/or denotational semantics.
Andrej Bauer is mainly arguing that Hask isn't a category because no one has formally specified it. For example, we would need to come up with a policy on when two arrows are considered equal, and it's not clear what that notion of equality should be.
A quote from Bauer's post is particularly relevant:
> [I am arguing against] the fact that some people find it acceptable to defend broken mathematics on the grounds that it is useful. Non-broken mathematics is also useful, as well as correct. Good engineers do not rationalize broken math by saying “life is tough”.
[0] https://leanprover.github.io/programming_in_lean/#01_Introdu...
[1] https://github.com/leanprover-community/mathlib/blob/master/...
I don't think there is a shortcut... these are highly abstract concepts.
Abstraction is about exposing the most essential parts of something... Category Theory is perhaps the mathematics of abstract composition, exposing the most essential parts of how to combine (in the abstract). Monad and Functor arise from CT, and thus, are very abstract concepts, built from the axioms of an already abstract subject matter. This is why it's hard to "simplify" them any further. The formal definition of a Monad is itself the simplest way to expose it. The fastest way to grapple with it is through the axioms of CT, precisely because CT is arriving at this concept by abstraction; by only thinking about the most essential parts of it.
That is probably not a satisfying explanation (to tell someone you need to learn axioms and laws before understanding this concept), but the alternative is to simplify and/or abstract something that is already as simple and as abstract as can be, albeit with esoteric names, and thus inevitably complicating it and shrouding the concept instead. i think the reason so many Monad tutorials aren't as satisfying is because they attempt to explain both a mathematical, abstract concept and also how it applies to programming, at the same time (without explicit separation). The latter is practical, the former is very abstract, and the bridge between them is very complex and usually left out, leaving the reader scratching their heads how and why you go from one to the other.
It's worth mentioning Bartosz Milewski here (links below), as he has bridged this gap for many, but as mentioned, there is no shortcut.
Upon hearing this, the islanders think that functions must be some magical panacea, and so you backtrack on that and try to talk about functions as being like animals, they take input and produce output (good luck with function composition).
The situation is like that with monads. They are far removed from the world of programming (the fact that there were connections at all to effects was remarkable!), but as such, you have to learn the ambient theory in which monads reside to really grok it.
If the author is reading this, I might make a suggestion: connect the hash map example to the function example.
Mathematically, a function is typically defined as literally a (potentially infinitely-long) map of unique keys (domain) to values (codomain). In programming, the two are not identical, especially in mutable languages, but the hash map example would be like memoizing function composition for a set of inputs specified as keys in the hash map.
> However, interfaces are adjectives that describe a data structure, which is why in many languages they are often named with -able suffixes (Iterable, Serializable, etc.) Programmers are better off thinking of it as Functable or Fmapable or something like that.
Fmapable makes much more sense to me. Naming is hard.
Worse... their usage in programming languages is very unlike how homomorphisms are typically used in their usual context, so appealing to the math seems like its just confusing learners without payoff.
To give an analogy... it feels like trying to explain the chain rule by explaining pullbacks between tangent spaces. Not technically wrong, but now they're confused and asking questions whose answers wont help them.
IME, category theory was much more valuable in differential topology in helping solidify why the structures and their compositional properties make sense. You get to work with several, honest-to-god categories and functors between them, especially when tangent bundles come into the mix.
Now go to programming, there's really only one category at play, and I'm not sure how worthwhile it is to apply a (more contrived) version of CT that only has endofunctors and being cartesian closed.
For programming... I feel like they're basically trying to do logic in a roundabout way. I suspect that (finite) model theory might be more useful for such applications if they really want theory.
I think it's a small convenience to have the programming language automatically derive `map` instances for you, but I think you're right for pretty much the same reason group theory's huge but monoid theory barely exists: the `Functor` typeclass is too simple to do anything interesting with it.
This puzzles me. It turns out it's very useful in the context of programming in practice (i.e. Haskell programmers use it and find it useful), so what do you mean? I don't know CT so I wouldn't know how well it maps (pun intended) with the Math concept, but regardless, whatever abstraction is there in Haskell that programmers call "functors" is tremendously useful.
For example, when using the Van Laarhoven free monad[0] implementation, I'll quantify over all monads. While, there is a simple data type definition for free monads[1], it suffers from a well-known issue that the bind operation has quadratic complexity. The Van Laarhoven free monad circumvents this problem (at least in the common case where you are not trying to "execute" the intermediate monadic constructions). There are also continuation-based approaches for free monad implementations as well.
The benefits of free monad are the typical ones described in "Data types à la carte" where you can, for example, instantiate your free monad in the IO monad for production, but use a pure monad instance for (parts of) your test harness.
(Generic implementations of free monads and their operations is another example of quantifying over all Functors, but I'm assuming for the sake of argument that you'd prefer to repeat that boilerplate over and over again for all your specific free monad instances.)
[0] http://r6.ca/blog/20140210T181244Z.html
[1] https://hackage.haskell.org/package/free-5.1.7/docs/Control-...
[2] http://www.cs.ru.nl/~W.Swierstra/Publications/DataTypesALaCa...
Example: I do mostly embedded prgramming, in Rust. My focus is on building working devices. I use abstractions and build APIs that are useful for solving specific problems I have now, or anticipate in the future. Eg an init function for an ADC that does the register writes described in the reference manual, so I can write `let adc = Adc::new()` instead of a series of reg writes.
It's common in embedded rust programming to make heavy use of generics, traits etc, and other things that leverage the type system to make it so that as many mistakes are caught at compile time as possible.
This sounds great in theory, but if a given abstraction makes type signatures a mess, doesn't allow me to configure a pin correctly due to an edge case, and provides no advantage if I QC I'm using the right pin, I won't use it. I see these Haskell examples as using abstractions by default, without questioning whether it's appropriate for a given use.
Because, a lot of the convenience and ergonomics that we can derive using these abstractions comes from being able to rely on the laws. Without them, they are just not really useful.
And when looking at the examples, I can totally see that someone reads
> That's all Monad is. It is an implementation of some "method" that conforms to that interface specification.
and then makes "Set" or "HashMap" implement the interface unlawful and bad things happen when they are least expected.
I label this my opinion quite on purpose, because I see the alternative viewpoint. I think you'll be more successful taking about lawfulness once someone gets the mechanics, given how much that has been a stopper over the years!
However, Monad and Functor are well defined terms. If you write an article where you complain about confusing explanations and try to do better, then you must start with a disclaimer: "I'm not explaining Monads as they are defined in math. I'm explaining something that is quite similar to it to make it more practical and later explain the actual term" or so.
Otherwise you are just adding to the confusion that people experience.
> The laws are less useful and less relevant in strict languages, as is the case with many laws, which is why Haskell programmers are just about the only ones discussing them.
I'm not sure if I would agree with that. But even if I would, the laws are still really important, even in strict languages. I've implemented quite a few monad instances in Scala (which is a strict language) and I'm speaking from experience.
(in case they are unfamiliar with the notation f : A -> B , then this can be explained in each of the first few examples.)
I guess it might also be good to give some counterexamples, and point out how the counterexamples fail to be functors, and why they are also not nice.
In the same way that we expect addition of numbers to obey the commutative law and associative law. (Except, of course, that floats don't...)
Implementing "unlawful monads" would be equal to giving someone a float and telling them "you can use this like a rational number from math". And in fact it might work for the longest time - until it doesn't (think rounding-errors and similar) and then the confusion will be big.
With monads it's the same, but potentially even worse, because it's rather easy to test float addition behavior, but for certain monads that can be much harder.
It gives a lot of theoretical background, but if you read the article here and already know the Optional-type and then you can skip it and go directly to "A Real World Example".
IIRC, Haskell relies on two out of the three, but I don't remember which two. But if you write a "monad" that doesn't satisfy them (even though it has the right function signatures), then you're going to get bogus results.
x+y+z is associative.
x-y-z is non-associative.
Functor, monoid and monad laws allow for undefined evaluation order, lazy evaluation, parallell execution and same results for same parameters. But only if the laws holds can such be guaranteed when using certain abstractions. Associativity being one obvious caveat that might break abstraction over collections, while using divide & conquer mechanics such as function currying.
Ie it's not just the interface that matters, but rules about the implementation.
> The problem is that a "do" block in the list monad chains together several of these flatMap calls. It is very easy for the transformation function to result in the computation growing exponentially as each one expands one item from before into one or more items. You have to have something else in the problem that prevents that from happening. You may see a lot of cute little algorithms like solving the n-queens problem, but in practice, this is not something you see used a lot in Haskell. The mathematical transform is cute, but hard to control because it's a bit too simple. In particular, this has no ability to "notice" that it is revisiting possibilities it visited before. That would take more machinery.
I think he's saying that it's doing a depth-first search without any caching. I'm wondering if Haskell has some other nice way of specifying depth-first searches that performs better?
This dialectic style adopted by the article for explanation is effective in exploring confused understandings. (Bit socratic) Not all writing needs to be technical writing like in a manual -- narrative explanations can be useful too.
Functor = map
Monad = flatMap
Did I understand the article correctly?
edit: this is an honest question. I way I read his explanation of Functor is that it's a function that implements map (list as input -> list as output).
His explanation of Monad said that its an input of List, where each item returns it's own List, then the function returns a flat List of all the results.
flatMap doesn't let you implement the audit log example, or work on a binary tree, let alone try to implement something like IO.
For all the functor tutorials, it really is nothing more than the interface and rules that define map. And Monad is essentially flatmap.
That's was so absurd about all of this.
"It is a common misconception that "monad is the same as flatmap", which has even made its way into some "monad libraries" in non-Haskell languages. flatmap is not "monad". flatmap is the particular implementation of the monad interface on lists. If you understand flatmap, you understand the monad implementation for the list datatype... you do not understand "monads" in general."
Maybe you think the author is wrong, but your comment didn't read like you were addressing these points.If you can read and understand this comment (https://news.ycombinator.com/item?id=27639779) then you understand 80% of the practical use of Monad.
And the majority of people who understand that comment, could now implement the flatMap/join/>>= for the "Maybe a" Monad. And could probably implement ">>" for it as well.
And if you can implement "bind" for a randomly requested Monad, while you may not know what a Kleisli Category is, nor be able to define the monad laws and might still make a mistake implementing one, you have the essential concept of a Monad.
Definitely not arbitrary but maybe not useful for many monads (??)
To be concrete, I'm talking about the kind with the semantics that if `Parser X` parses an `X`, and `Parser Y` parses a `Y`, `>>` between them parses an X then a Y. I propose that you must explain that in terms of flatMap in order to say that this is a correct understanding of monads.
flatMap() is a specific function that you already understand. It is the most common instance of a general fn pattern that is used for the specific data type Array.
The flatMap equivalent function when used on the data type Promise is called then().
The special function you are asking to understand ">>" is simply another instance of then(). This one still waits for the promise to complete - the only difference is that the lambda you pass to then() doesn't have access to the result of the previous promise.
If you're using >>/flatMap on a Parser datatype, instead of running the lambda after first promise has completed successfully, it "runs" it after the first parser has completed successfully.
flatMap and (all of its other data type specific names) are the essence of a Monad.
What I am still unclear on is the difference between applicative and monad. Both, to my mind, have this concept of combining "wrapped" values. Currently my intuition for the two is exactly the same. So my intuition is probably wrong.
I would love a similar explanation to this post on applicative vs monad.
Functors let you chain together unary (non-branching, straight line) processing pipelines. If your processing pipeline works over any functor, then it can be applied to any structure that acts as a source of values, and it will leave that structure unchanged around the processed data.
An "applicative" is a functor that also lets you take two values, one structuring some `a`s and one structuring some `b`s, and cross them together to produce a result that structures some tuples `(a, b)`. If I have two lists, I can cross them together to get a list of all pairs of elements between the two lists (like a CROSS JOIN in SQL).
Applicatives let you merge two separate processing pipelines together, combining data from both sides together into a single stream. If you can combine two pipelines into one, you can combine any number of them; this is what makes them strictly more powerful than general functors, which cannot support multiple parallel data sources.
A "monad" is a functor that also lets you take a value with two layers of nested structure, `f (f a)`, and meld/flatten/unify those two layers into a single layer of the same kind (`f a`). If I have a list of lists, I can unwrap the inner list structures, lifting all of their elements to the top level. Or, more viscerally (for me), if I have a binary tree whose leaves contain binary trees, I can graft the inner tree at each leaf onto the outer tree, producing a deeper single tree.
Monads let you accumulate some inner structure produced by a stage of your pipeline into the outer structure your values came from. In turn, this reveals the values under the inner structure to downstream pipeline elements.
The community is very much focused on learning, by teaching the little one knows.
So far all I got from this is that functors are functions?
- a parametrized type, like for instance List: you can have lists of integers, floats, functions, or any other type
- a way of mapping (in the sense of List.map) between instances of the parametrized type, given regular functions. This mapping should behave nicely with respect to regular function composition.
If your parametrized type is F, then the mapping operation turns ("lifts") regular functions A -> B into functions (F A) -> (F B) in a reasonable way: "if you give me a function then I can transform any list using it".
Functors can be used to "decorate" values: you can model exceptions (some value or an error), promises (some value not yet computed), state (some value + side effects) and many other kinds of effects using functors.
So in general an effectful computation will have type A -> (F B) for some functor F modeling the effect. And now you have a problem: how to compose effectful computations in order to build larger programs out of smaller ones? You cannot simply compose A -> (F B) with B -> (F C) since the types don't match.
What you need is a way of transforming an effectful computation B -> (F C) into a lifted function (F B) -> (F C) so that you can compose A -> (F B) with (F B) -> (F C) in order to get A -> (F C).
That device should satisfy some properties to make effectful composition work the way you expect (in particular there should exist identity effectful computations), and is called a monad.
A monad is a functor + some extra operations (bind/return) satisfying properties that will make effectful computations (using this functor) composable.
The type of bind is generally written (F A) -> (A -> F B) -> (F B) but really it is the same as (A -> F B) -> (F A -> F B) above (takes an effectful computation, gives back a lifted function).
Here's my best understanding so far:
A functor is a function that takes in a list of things and like a regular function, outputs a list of modified things...
So how is this different from a function?
To give a simpler example, we say a function, f, is monotone when for x<y, f(x)<f(y); that is, it preserves order. Every monotone function is obviously a function, but functions like x^2 are not monotone.
Basically a functor is a function which preserves some other properties. I wont go into detail as many have before me, but thats the gist.
isn't this just applicative? What is needed to turn applicative into monad?
I dont want to discourage you from learning math, but I think this isnt a good place spend too much thought at first.
I've heard a bunch of people say that category theory is almost like a 'bird's eye view of mathematics'. That many of its concepts unify many mathematical concepts under one umbrella, and reveal the similarities and connections between mathematical subdisciplines.
The main reason this interests me is that I'd like to learn math much differently than its taught.
To me, to learn the same concept under different subdisciplines with different names, is O(N) learning.
However, if someone put together a category theory book where they list a concept, and then they do this:
"Now, any mathematician can (easily) see that every major area of mathematics is a category.
- In Set Theory the arrows are functions
- in Topology they are continuous functions
- in Group Theory homomorphisms
- in Linear Algebra they are linear transformations
- in Differentiable Geometry they’re smooth maps, and so on…
But what’s important is that we shifted from focusing on the objects to focusing on the functions, the ways in which we transform the objects. This is basically the category-theoretical perspective: it’s the functions that matter."
(Taken from this blogpost: https://catsinthejungle.wordpress.com/2008/11/15/category-th... )
Do I understand any of that? No. But what attracts me to this format is it (MAYBE...) approximates O(1) learning in math, so long as it can also point out, for every concept in every field, how they differ/relate to every other concept.
So what this does is it helps teach me the 'unifiers' of mathematics, and helps me see connections between fields which can be useful for creativity. E.g. I realize I'm doing X algorithm here from linear algebra and that is O(N), whereas if I just shift fields, and use Y algorithm from Group theory I might make it O(log n) because it differs in this way or whatever it is.
Besides that I see it as a potentially efficient way of learning a lot of math.
While a shortcut to understanding sounds nice, I don't think you'll find it by focusing on abstract formalism.
I prefer to just write down the type and stare at it and think about what sort of functions could have that type. Later you can look at the rules. And this mostly means one needs to have written a little (eg) Haskell so that the one can read simple types. The signature of fmap looks like:
fmap :: (a -> b) -> functor a -> functor b
It should easy to guess what sort of types and functions could satisfy that. The rule restricts the possibilities more: fmap (\x -> f (g x)) a == fmap f (fmap g a)While monads as a general interface might not be in your favorite language, individual implementations of monads might very well be. JS Promise, C# Task and Rust Future are all asynchrony monads - their bind is .then / .ContinueWith / .and_then respectively (with some caveats; the first two overload their bind to also work as fmap).
In practice it's not too much of a problem, but it does mean that if you use some FP library, you cannot trivially wrap a promise to make it a monadic type that will work with the library's monad utilities.
There's a bunch of history in [1], particularly [2] and [3], if you care to read them.
[1]: https://github.com/promises-aplus/promises-spec/issues
[2]: https://github.com/promises-aplus/promises-spec/issues/75
[3]: https://github.com/promises-aplus/promises-spec/issues/94
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
Now, I am comfortable with upper case for type and lower case for instance.But m is an instance of a function, not a variable. But m, a, and b all look like variables. You are already hammering me with the brevity here.
Maybe put the functions in a serif font, and variables in a sans-serif? Or use different colors? Other languages seem to be more helpful with the visual cues.
Solving problems in SQL is a blast, so it seems like Haskell should be an easy lift, but the brevity of the syntax has sent me packing for years.
Monad is a typeclass, not a type. m is a variable, whose value is a type constructor.
> But m is an instance of a function, not a variable.
On the type level, m is a variable representing a type constructor; a concrete value it might have is List. It is an instance of a typeclass, not a function.
> But m, a, and b all look like variables.
m, a, and b are all type-level variables; the value of m is a type constructor (which is essentially a type-level function), while the values of a and b are types.
Let's try to apply that knowledge, and use my tribe's creed that "similar things should look similar, and different things should look different":
-- α, β types
-- m type constructor
(>>=) :: m α -> (α -> m β) -> m β
-- a, b types
-- 𝘮 type constructor
(>>=) :: 𝘮 a -> (a -> 𝘮 b) -> 𝘮 b
I think that's much better. GP's complaint was correct, writing different concepts with the same notation is confusing.It's hard to find best intro material. The above could scare away someone else, even Haskellers.
Maybe intro on how to read examples, explanations etc. could aide?
If it were a physical building, Haskell would be brutalist.
I think it’s better to at least try to make a name that transmits partial meaning or a general gist of the idea.
If we didn’t use formal terms for math concepts, mathematicians would waste all their time arguing about the colloquial definitions of the colloquial words they tried to map onto abstract concepts. It’s better to have a clean break and force people to learn the specific formal meaning rather than try to limp along on a busted half-intuition.
similarly, monads bear a strong resemblance to monoids - in fact, it's the same relationship as functions and functors and it's quite precise. these intuitions only become available to you with the math, though, and programmers have a strange aversion to mathematics for people who do it day in and day out.
This sentence from it sums up many of my conversations about FP
It probably also doesn't help that we have a function literally called >>=, which is hard to pronounce. It's pronounced "bind", which is only slightly more helpful in that that still fails to evoke any useful imagery
One question on functor: Does the thing returned have to be "the same shape" as the original? That is, if I have a list, and I fmap on it, do I always get a list back? Or am I only guaranteed to get some kind of functor back? If I am guaranteed to get a list back, am I guaranteed that it has the same number of elements?
To use your initial language, is it fair to say that a functor takes a source of a, and a function that converts a to b, and returns a source of b of the same "shape" as the original source of a?
If it's true, that makes the function example clearer to me. Of course it has to return a function, because the shape of the input was "function".
(And, did the article answer this and I just missed it?)
fmap :: (a -> b) -> f a -> f b
The `a` becomes a `b` (which could be a different type but not necessarily), but the `f` is the same `f`.I've recently been interested in learning more math to apply to programming. Does anyone here on HN know where I can find quality education online (free) I can use through the rest of the summer? I only got to geometry as my highest maths in high school.
- "return x" produces a I/O operation that does nothing and produces the result x.
- "x <$> y" or "fmap x y" produces a I/O operation that does the same thing as y, but the result value is the function x applied to the result of y.
- "x >>= y" produce a I/O operation that when performed, performs x, and then passes the result to the function y, which returns the I/O operation to be performed next.
- "join x" takes the I/O operation x which has the result which is itself a I/O operation; the new one first does x and then the I/O operation which is the result of x.
A I/O operation might have different results when performed multiple times, even if it is the same I/O operation.
Also, I can say that generators in JavaScript seem to form two different monads actually (as far as I can tell), as described by the following table:
yield x yield*x
return x return yield*x
Also, functors and monads are more than the interface, but also the mathematical properties they have (such as "fmap id = id" etc).There is nothing inherently interesting about functors and monads. Haskell, as a research project, discovered that you could isolate IO in a lazy language inside a type using a monadic construction to chain them which allows you to track side effects. That was interesting, the rest less so.
Now the Haskell community somewhat fetishized these abstractions for reasons which are their own. They must be apparent to the community at large. They are not to me.
Sounds like LINQ in C#. I wonder if there's any correlation.
I personally don't think Haskell stand at the right level of abstraction but that's a personal opinion.
a <- method b
c <- method a
is equivalent to
a = await method(b)
c = await method(a)
Again. Use javascript to learn Monad in real world is a better way to learn.
It's like having someone run hello world in java and declaring they know what 'static' means.
Also, JS promises are not really monads. They lack denotational equality, so they can’t be said to obey the monad laws.
(I know, I know - your environment is a special case).