2

I am relatively new to Haskell and have struggled to find some clarification on this confusion.

Given a function that takes an Integer as an input, what would be the difference between the function returning State Integer () and State Int Integer.

I think I am right in understanding that State Int Integer requires me to return the result using the pure function.

When I try to write a function of func :: Integer -> State Integer () I get the error No instance for (Num ()) arising from the literal ‘0’, as I try to use pure to return the value 0.

JFMR
  • 23,265
  • 4
  • 52
  • 76
amduck
  • 21
  • 5

1 Answers1

1

First of all a common misconception is that State a b contains state. It does not, it changes a state. Indeed, something of a State a b will take a state of type a might change the state (to pass to the next State object), and might "return" some value of type b.

If you thus have a function helper1 :: State Int String for example, and a function helper2 :: String -> State Int () you can pass the String that will be returned by the State object of helper1 to construct a State object of helper2, so you can make a function:

func :: State Int ()
func = do
  s <- helper1
  helper2 s

Both helper1 and helper2 s can read the state that will be passed, modify the state, or might for example return the state. But nor func, helper1 and helper2 contain a state. What you can do is work with runState :: State s a -> s -> (s, a). Here you provide an initial state, and you run that state through func for example. We can thus call runState func 0 to run this "through" func with initial state 0. It will then return a 2-tuple with the state after it has passed through func and what func returns (in this case the unit value).

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555