by avalys · 5y ago · 0 comments
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.
I would really like to understand what they are, but so far have not been able to find any explanation which tries to explain them in terms of english, math or some commonly known programming language.
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).