hemanth / functional-programming-jargon

Jargon from the functional programming world in simple terms!
http://git.io/fp-jargons
MIT License
18.58k stars 1.02k forks source link

Add explanation about Kleisli #161

Closed wisn closed 2 years ago

wisn commented 7 years ago

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?

jethrolarson commented 7 years ago

Would be a good addition. Someone needs to break concept down to eli5 levels and then provide one or two examples

wisn commented 7 years ago

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.

MostAwesomeDude commented 2 years ago

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.

jethrolarson commented 2 years ago

Let me try so break it down:

Kleisli Composition

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:

jethrolarson commented 2 years ago

Admittedly array is a poor case and using Option or Either would be more practical.

const validateFooAndBar = kleisliCompose(validateFoo, validateBar)