Closed wisn closed 2 years ago
Would be a good addition. Someone needs to break concept down to eli5 levels and then provide one or two examples
There is a good reading material on nLab about Kleisli category. I'm still try to learn this. Maybe someone willing to use it as a reference.
I can explain it, at least; I don't know of especially good examples.
Typically, we have functions, say of type X → Y. With a monad M, we might have actions ("impure" functions) in the monad, of type X → M(Y). Composition with functions happens to form a category: there is an identity arrow of type X → X (for any type X) which obeys the algebraic laws. Can we analogize this to monadic actions?
Yes, for any monad M. Kleisli composition lets us compose actions of type X → M(Y) and Y → M(Z) into actions of type X → M(Z), for any types X, Y, and Z. The identity arrow is provided by the unit of the monad, with type X → M(X).
I don't know when this is useful aside from "compiling to categories", a not-yet-common design for compiler pipelines. It probably could wait another few years.
Let me try so break it down:
An operation for composing two monad-returning functions where they have compatible types.
const foo = (a) => [a]
const bar = (b) => [b*2, b*3]
kleisliCompose(bar, foo)(1) // => [1, 2, 3]
This works because:
foo
and bar
return the same kind of monad (Array)bar
is the same as the type within the array of foo
s return.Admittedly array is a poor case and using Option
or Either
would be more practical.
const validateFooAndBar = kleisliCompose(validateFoo, validateBar)
I found something like Kleisli composition (
>=>
in Haskell) in Quora. I don't really understand the general of Kleisli. Based on Quora, Kleisli composition is a monadic function composition (CMIIW). How about this?