7. de nition of Monad in Haskell
GHC.Base#Monad
class Applicative m => Monad m where
(>>=) :: forall a b. m a -> (a -> m b) -> m b
(>>) :: forall a b. m a -> m b -> m b
m >> k = m >>= _ -> k
{-# INLINE (>>) #-}
return :: a -> m a
return = pure
fail :: String -> m a
fail s = errorWithoutStackTrace s
10. e.g. scala.Option
scala> val a = Some(2)
a: Some[Int] = Some(2)
scala> val b = Some(3)
b: Some[Int] = Some(3)
scala> a.flatMap { x => // with `flatMap` & `map`
| b.map { y =>
| x * y
| }
| }
res0: Option[Int] = Some(6)
scala> for { // with `for` expression
| x <- a
| y <- b
| } yield x * y
res1: Option[Int] = Some(6)
11. e.g. Prelude.Maybe
> a = Just 2
> b = Just 3
> :{ -- with `>>=` & `return`
| a >>= x ->
| b >>= y ->
| return $ x * y
| :}
Just 6
> :{ -- with `do` notation
| do
| x <- a
| y <- b
| return $ x * y
| :}
Just 6
12. e.g. cats.monad.maybe
user=> (require '[cats.core :as m]
#_=> '[cats.monad.maybe :as maybe])
nil
user=> (def a (maybe/just 2))
#'user/a
user=> (def b (maybe/just 3))
#'user/b
user=> (m/>>= a (fn [x] ; with `>>=` & `return`
#_=> (m/>>= b (fn [y]
#_=> (m/return (* x y))))))
#<Just 6>
user=> (m/mlet [x a ; with `mlet` macro
#_=> y b]
#_=> (m/return (* x y)))
#<Just 6>
37. without monads
naïve implementation
(defn- folding-function [[x y & ys :as xs] s]
(cond
(and x y (= s "*")) (conj ys (* y x))
(and x y (= s "+")) (conj ys (+ y x))
(and x y (= s "-")) (conj ys (- y x))
:else (conj xs (Double/parseDouble s))))
(defn solve-rpn [s]
(as-> s v
(str/split v #"s+")
(reduce folding-function () v)
(first v)))