A monad provides a way to sequence computations where a result determines what happens next. In Idris, the Monad interface makes this sequencing available through the (>>=) operator and do notation. section 7.3.3 section 7.4
interface Applicative m => Monad (m : Type -> Type) where #1 (>>=) : m a -> (a -> m b) -> m b join : m (m a) -> m a
The type of (>>=) is a plan for sequencing: take a computation producing an a, then a function that uses that a to produce the next computation. The join operation combines a nested monadic structure into one. section 7.3.3
The meaning of sequencing depends on the implementation. For IO, it sequences interactive actions. For Maybe, it can abandon the remaining computation when a result is Nothing. For List, it passes each input value to the next function. section 7.3.3
Monad Maybe where
(>>=) Nothing next = Nothing
(>>=) (Just x) next = next x
The Maybe implementation makes failure propagation explicit: Nothing stays Nothing, while Just x passes x to the next computation. section 7.3.3
Monad requires Applicative, which provides pure to put a value into a computation and (<*>) to apply a function inside a structure. Functor is also required by Applicative. Both (>>=) and join have defaults, so a Monad implementation can define either one. section 7.3.3 section 12.2.2
Applicative (State stateType) where pure = Pure (<*>) f a = Bind f (\f' => #1 Bind a (\a' => #2 Pure (f' a'))) #3 Monad (State stateType) where (>>=) = Bind #4
For a custom State type, the Monad implementation can define (>>=) as Bind. Implementing Applicative as well makes generic library functions available alongside do notation. section 12.2.2
addIfPositive : Integer -> State Integer Bool addIfPositive val = do when (val > 0) $ #1 do current <- get put (current + val) pure (val > 0) #2 addPositives : List Integer -> State Integer Nat addPositives vals = do added <- traverse addIfPositive vals #3 pure (length (filter id added)) #4
This State example uses when to add only positive integers and traverse to process a list. Running addPositives on [-4, 3, -8, 9, 8] with initial state 0 returns (3, 20): three values added and a total of 20. section 12.2.2







