This example is very intuitive. There are 3 cases for xs, which are empty list, list with only 1 element and list with more than 1 element.
describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list."
But I get lost in the following code
newtype State s a = StateOf{deState :: s -> (s, a)}
postInc :: State Int Int
postInc = StateOf (\i -> (i+1, i))
instance Monad (State s) where
return a = pure a
StateOf t >>= k = StateOf (\i0 -> case t i0 of
(i1, a) -> deState (k a) i1)
I totally don't know what i1
and a
represent.
Haskell uses two data structures for managing several values: lists and tuples. Tuples have fixed length and don't need to be of the same type:
(1, "2") :: (Int, String)
You also can pattern match the values of the tuple. Just for an example:
nonBlank :: (Int, String) -> Bool
nonBlank tuple =
case tuple of
(0, _) -> False
(_, "") -> False
_ -> True
This line declares State
, which stores a function, which receives an argument and returns a tuple:
newtype State s a = StateOf{deState :: s -> (s, a)}
And this line defines >>=
function for this type:
StateOf t >>= k = StateOf (\i0 -> case t i0 of
(i1, a) -> deState (k a) i1)
You probably confused by the t i0
, but actually, when you understand, that the type of t
is a function s -> (s, a)
, then it's clear that t i0
returns a tuple, which you can pattern match.