--- Recommended reading: -- -- https://haskellforall.com/2014/10/how-to-desugar-haskell-code -- https://jstolarek.github.io/files/stolarek_understanding_basic_haskell_error_messages.pdf --- Additional reading: -- -- https://serokell.io/blog/haskell-to-core -- https://aosabook.org/en/v2/ghc.html --- A free Haskell textbook: Real World Haskell -- -- https://github.com/tssm/up-to-date-real-world-haskell -- https://web.archive.org/web/20221207035126/https://book.realworldhaskell.org/read/ {- Let's think of the Monad's >>= as a style of programming where calculation happens via a pipeline of functions, with values and errors passed down that pipeline. More generally, the "state" of the program is passed down that pipeline. In this pipeline, there are basic types we work with, e.g., Int, Char, String, and the more complex types we made out of them, e.g., Maybe, IO, State. We operate on basic types, but, because our operations may fail or have side effects, results end up in the respective complex type. This is the idea behind the operations having the type signature a -> m b : we take an 'a' and hope to make a 'b', but we actually get an 'm b' because of whatever more complex behaviors motivated our creation of the complex type 'm b', such as the possibility of failure (e.g., Maybe) or side-effects (e.g., IO). Let's say our pipeline would do work on a, b, c, etc., with a->b, b->c, etc. Then our >>= pipeline operations will be a -> m b, b -> m c, etc. They go _diagonally_ in the diagram M a -> M b -> M c -> ... ^ / ^ / ^ / | / | / | / | / | / | / a -> b -> c -> ... Vertical arrows in this diagram are the constructors of each monad for objects, or, most conveniently, "return" that conveniently makes an 'M a' out of 'a'. Diagonal arrows are the function you find right of >>= . Recall that fmap, if defined for the type M, would lift functions a->b to (M a -> M b). That's quite not what we want for the processing pipeline, see below. On the left at the start of the chain is the monadic value where the processing starts. Note that >>= associates to the _left_, so m >>= f >>= g >>= h >>= ... is (((m >>= f) >>= g) >>= h) >>= ... This syntax makes perfect sense: the monadic value is always on the left of >>=, the action is on the right, and so the chain continues. For inputs, the starting value is of a type IO String, IO Char, etc. and gives the first function in the chain the String or Char to work on. For example, a pipeline may start with "getLine >>= ..." or "getChar >>= ..." which create the IO String and IO Char respectively. For list operations that may fail (recall Maybe types in Data.List), the first value may the result of an index operation or a 'Just x' value. Let's look at some pipelines: -} -- This index function crashes if the index is wrong, a.k.a. (!!) is not a total function. ghci> :i (!!) (!!) :: GHC.Internal.Stack.Types.HasCallStack => [a] -> Int -> a -- Defined in ‘GHC.Internal.List’ infixl 9 !! ghci> "abcdef" !! 10 *** Exception: Prelude.!!: index too large HasCallStack backtrace: error, called at libraries/ghc-internal/src/GHC/Internal/List.hs:1627:14 in ghc-internal:GHC.Internal.List tooLarge, called at libraries/ghc-internal/src/GHC/Internal/List.hs:1637:50 in ghc-internal:GHC.Internal.List !!, called at :50:10 in interactive:Ghci7 --- (!?) is total, at the cost of producing a Maybe where (!!) produces a simple type: ghci> :i (!?) :1:1: error: [GHC-76037] Not in scope: ‘!?’ -- oops, need Data.List ghci> import Data.List ghci> :i (!?) (!?) :: [a] -> Int -> Maybe a -- Defined in ‘GHC.Internal.List’ infixl 9 !? ghci> "abcdef" !? 10 Nothing ghci> "abcdef" !? 3 Just 'd' -- (!?) is perfect for monadic pipelines: real indexes get a match or fail, -- starting with a Nothing makes it sail right through: ghci> take 26 ['a'..] -- I ran ['a'..] first and got "abcdefghijklmnopqrstuvwxyz{|}~\DEL\128\129\130\131\132\133\134\135\136\137[..skipped..] " ghci> let az = take 26 ['a'..] "abcdefghijklmnopqrstuvwxyz" ghci> :t az az :: [Char] ghci> Just 10 >>= (!?) az Just 'k' ghci> Nothing >>= (!?) az Nothing ghci> :t (az !?) (az !?) :: Int -> Maybe Char -- We can't pass straight-up non-monadic values through >>= : ghci> 3 >>= (!?) az :5:1: error: [GHC-39999] • No instance for ‘Num (Maybe Int)’ arising from the literal ‘3’ • In the first argument of ‘(>>=)’, namely ‘3’ In the expression: 3 >>= (!?) az In an equation for ‘it’: it = 3 >>= (!?) az -- But this works (return infers the right type): ghci> return 3 >>= (!?) az Just 'd' -- BTW, (az !?) is naturally a closure, independent of what az might become later: ghci> let az_ind = (az !?) ghci> let az = "abc" ghci> az_ind 10 Just 'k' ghci> az_ind 25 Just 'z' ghci> az_ind 26 Nothing --- Compare the above with functors. --- Fmap will lift az_ind to Maybe Int -> Maybe (Maybe Char) : ghci> :t fmap (az !? ) fmap (az !? ) :: Functor f => f Int -> f (Maybe Char) ghci> (fmap (az !? ) ) Nothing Nothing -- 10 is not a Maybe Int, so this fails: ghci> (fmap (az !? ) ) 10 :61:1: error: [GHC-39999] • Ambiguous type variable ‘f0’ arising from a use of ‘print’ prevents the constraint ‘(Show (f0 (Maybe Char)))’ from being solved. Probable fix: use a type annotation to specify what ‘f0’ should be. Potentially matching instances: instance (Show a, Show b) => Show (Either a b) -- Defined in ‘GHC.Internal.Data.Either’ instance Show a => Show (Maybe a) -- Defined in ‘GHC.Internal.Show’ ...plus 16 others ...plus two instances involving out-of-scope types (use -fprint-potential-instances to see them all) • In a stmt of an interactive GHCi command: print it -- Once we supply a (Just 10) or (return 10) we get it to run---but notice -- the extra Just on the result: ghci> (fmap (az !? ) ) (Just 10) Just (Just 'k') --- So fmap is not quite what we want. You might ask, can't we "flatten" the extra Just? --- The answer is that there is no well-defined total way of going down from a Maybe, --- because what if you get a Nothing? Still, Haskell defines a non-total function --- fromJust: Maybe a -> a that _will_ crash if you feed it a Nothing, but would --- got from a (Just 10) to 10: ghci> import Data.Maybe ghci> :t fromJust fromJust :: GHC.Internal.Stack.Types.HasCallStack => Maybe a -> a ghci> fromJust (Just 5) 5 ghci> fromJust (return 5) 5 ghci> fromJust Nothing *** Exception: Maybe.fromJust: Nothing HasCallStack backtrace: error, called at libraries/ghc-internal/src/GHC/Internal/Data/Maybe.hs:150:21 in ghc-internal:GHC.Internal.Data.Maybe fromJust, called at :24:1 in interactive:Ghci12 -------------------------- Let's see how >>= works with IO -------------------------- -- We get input lines from getLine, which makes an IO monadic object. Everything about -- this object is opaque (understandably so, because system's input-output is full -- of states and effects), but it gives us one thing, a String we can get through >>= . ghci> :t getLine getLine :: IO String -- So how do we use this string? This is close but doesn't quite work: ghci> getLine >>= (\s -> "Hello " ++ s) :70:20: error: [GHC-83865] • Couldn't match type ‘[]’ with ‘IO’ --- the expected type must be an IO _ Expected: IO Char Actual: [Char] • In the expression: "Hello " ++ s In the second argument of ‘(>>=)’, namely ‘(\ s -> "Hello " ++ s)’ In the expression: getLine >>= (\ s -> "Hello " ++ s) -- Remember, we need to return a monadic type! ghci> getLine >>= \s -> return ("Hello " ++ s) Foo "Hello Foo" -- or, equivalently, ghci> getLine >>= return . (\s -> "Hello " ++ s) Foo "Hello Foo" -- Note the resulting type, it's IO [Char]: ghci> :t getLine >>= \s -> return ("Hello " ++ s) getLine >>= \s -> return ("Hello " ++ s) :: IO [Char] -- We could also call a printing function which drives us into another monadic type, IO () -- () can be understood as "nothing useful"; the characters are printed and gone. ghci> getLine >>= \s -> putStrLn ("Hello " ++ s) Foo Hello Foo --------------------- "DO" notation --------------------- >>= often needs a lambda on its right side. This gets tedious, so there's some syntactic sugar for it that makes the code look more imperative (think C's ';') m >>= \x -> f is do x <- m f x Also recall that m >> f is m >>= \_ -> f , i.e., f disregards arguments --- Let's look at more examples: {- read-string.hs echo = getLine >>= \s -> putStrLn ("Echo " ++ s ) >>= \_ -> putStrLn ("Done") -- Exactly equivalent: echo1 = getLine >>= \s -> putStrLn ("Echo " ++ s ) >> putStrLn ("Done") -- The same with 'do' notation. It hides the lambdas, but they're still there. echo2 = do str <- getLine putStrLn( "Hello " ++ str ) putStrLn( "Done" ) -- Now we don't just echo a string but _parse_ it into a number (a Double). -- Note the very first explicit type declaration ::Double that tells the -- polymorphic read what to expect and which specialized parsing function -- to call. double = do putStrLn "Please enter a Double:" inpStr <- getLine let inpDouble = (read inpStr)::Double -- here we parse a string into a Double putStrLn ("Twice " ++ show inpDouble ++ " is " ++ show (inpDouble * 2)) -} ghci> :l read-string.hs [1 of 2] Compiling Main ( read-string.hs, interpreted )[interactive-session] Ok, one module loaded. ghci> echo Bar Echo Bar Done ghci> :t read read :: Read a => String -> a ghci> double Please enter a Double: 3.0 Twice 3.0 is 6.0 ghci> double Please enter a Double: a Twice *** Exception: Prelude.read: no parse ghci> double Please enter a Double: .3 Twice *** Exception: Prelude.read: no parse ghci> double Please enter a Double: 0.45656 Twice 0.45656 is 0.91312 {- We get characters from getChar and lines from getLine. In fact, getLine calls getChar until it sees an end-of-line. In the true Haskell fashion, it does so recursively, tail-calling itself for each character it reads: {- From the standard Prelude https://www.haskell.org/onlinereport/standard-prelude.html getLine :: IO String getLine = do c <- getChar if c == '\n' then return "" else do s <- getLine return (c:s) which desugars to getLine = do c <- getChar if c == '\n' then return "" else getLine >>= \s -> return (c:s) and further to getLine = getChar >>= \c -> (if c == '\n' then return "" else getLine >>= \s -> return (c:s) ) -} {- Recall again that >>= associates to the left: m >>= f >>= g >>= h >>= .. is (((m >>= f) >>= g) >>= h) >>= .. as expected. So this pipeline for IO somewhat resembles C++'s stream operators >> . -} {- Let's take a look at putStr -- it maps putChar over its argument string, as per the reference Prelude code, https://www.haskell.org/onlinereport/standard-prelude.html putStr :: String -> IO () putStr s = mapM_ putChar s Except the map must itself be monadic because every character can create side effects or errors. So we look it up: mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ f as = sequence_ (map f as) putChar here is f and matches (a -> m b) because it is Char -> IO () , with a==Char, b=() So we get sequence_ putChar s , where s is [Char] sequence_ :: Monad m => [m a] -> m () sequence_ = foldr (>>) (return ()) foldr (>>) (map putChar s) then unfolds (lazily!) into putChar c0 >> putChar c1 >> putChar c2 >> .... where s = c0 : c1 : c2 : ... After this putStrLn is just a >> : putStr s >> putStr "\n" , or, equivalently putStrLn :: String -> IO () putStrLn s = do putStr s putStr "\n" This point about foldr is beautifully made in https://blog.haskell.org/foldl-and-foldr/ . Now mapM and sequence look a lot more complicated, but very worth understanding! See https://www.haskell.org/onlinereport/standard-prelude.html and try to figure it out. Submit your explanation for extra credit :) -} {- An aside: show is a pure function that creates printable (i.e., String) representations of objects. It is the pure part of the monadic print. ghci> show 1 "1" ghci> :t show show :: Show a => a -> String ghci> show 1 : 2 : [] --- oops, that's (show 1) : 2 : [] and fails :66:10: error: [GHC-39999] • No instance for ‘Num String’ arising from the literal ‘2’ • In the first argument of ‘(:)’, namely ‘2’ In the second argument of ‘(:)’, namely ‘2 : []’ In the expression: show 1 : 2 : [] ghci> show (1 : 2 : []) "[1,2]" --- standard print representation Remember: Unlike Lisp and Scheme, there is no guarantee that printed representations would parse back. -} {- An aside about terms borrowed from Algebra and Category theory: Sooner or later you will hear that Haskell's Monad has something to do with Endofunctors and Monoids. This is a fancy way of saying that >>= operations chain up and work well with Haskell's function types (which, as you recall, are "first class", algebraic, and are made on demand). An entertaining note about this topic is found here: https://stackoverflow.com/questions/3870088/a-monad-is-just-a-monoid-in-the-category-of-endofunctors-whats-the-problem Note, though, that the use of these terms is not quite precise: Haskell concepts resemble mathematical ones, but don't exactly implement them. -}