Mathieu Ledru
September 30, 2021
1.6k

# Monads and usage in PHP

Monads exemple code associated to this talk

https://github.com/darkwood-fr/flow

Article associated to this talk

Video associated to this talk

## Mathieu Ledru

September 30, 2021

## Transcript

4. ### “Once you understand Monads You lose the ability to explain

them to other people” Crockford’s Paradox “ @matyo91 29-09-2021

6. ### Data Expr = Val Int | Div Expr Expr @matyo91

@matyo91 29-09-2021
7. ### Math world 1 6 / 2 6 / ( 3

/ 1 ) @matyo91 @matyo91 29-09-2021 Haskell world Val 1 Div (Val 6) (Val 2) Div (Val 6) (Div (Val 3) (Val 1))
8. ### eval :: Expr -> Int eval (Val n) = n

eval (Div (Expr x) (Expr y)) = eval(x) / eval(y) @matyo91 @matyo91 29-09-2021
9. ### safediv :: Int -> Int -> MayBe Int safediv (Int

n) (Int m) = if m == 0 then Nothing else Just(n / m) @matyo91 @matyo91 29-09-2021
10. ### eval :: Expr -> Maybe eval (Val n) = Just(n)

eval (Div (Expr x) (Expr y)) = case eval(x) at Nothing -> Nothing Just n -> case eval(y) of Nothing -> Nothing Just m -> safediv (n m) @matyo91 @matyo91 29-09-2021
11. ### case [m] as Maybe of Nothing -> Nothing Just x

-> [f] as function x @matyo91 @matyo91 29-09-2021
12. ### m >>= f case m of Nothing -> Nothing Just

x -> f x @matyo91 @matyo91 29-09-2021
13. ### eval :: Expr -> Maybe Int eval (Val n) =

return n eval (Div (Expr x) (Expr y)) = eval(x) >>= (ƛn -> eval(y) >>= (ƛm -> safediv n m)) @matyo91 @matyo91 29-09-2021
14. ### eval :: Expr -> Maybe Int eval (Val n) =

return n eval (Div (Expr x) (Expr y)) = do n <- end x m <- end y safediv n m @matyo91 @matyo91 29-09-2021
15. ### return :: a -> Maybe a >>= :: Maybe a

-> (a -> Maybe b) -> Maybe b @matyo91 @matyo91 29-09-2021

18. ### “Go learn Haskell” “Go learn Category Theory” “A monad is

just a monoid in category of endofunctors” (M t) -> (t -> Mu) -> (M u) (>>=) :: (Monad m) => m a -> (a -> m b) -> m b What is a Monad? @matyo91 @matyo91 29-09-2021
19. ### I don’t fully understand them I will share what I’ve

learned so far You fill in the blanks Monads are a loophole in the “Functional contract” A way to write pure functions with referential transparency The loophole @matyo91 @matyo91 29-09-2021

21. ### function unit(\$value) function bind(\$monad, function(\$value) { … }) \$value passed

to function in bind <=> \$value passed to unit All return a new monad Function that returns new thing <=> constructor All monads are constructors Not all constructors are monads Unit & bind @matyo91 @matyo91 29-09-2021

\$fnB)     <=>     bind(\$monad, function(\$value) {   return bind(\$fnA(\$value), \$fnB);   }) Axioms @matyo91 @matyo91 29-09-2021
23. ### OOP @matyo91 @matyo91 29-09-2021

\$monad->bind(function(\$value) {   return \$fnA(\$value)->bind(\$fnB);   }) Axioms of class @matyo91 @matyo91 29-09-2021