[Haskell-beginners] State in IO monad

Dmitriy Matrosov sgf.dma at gmail.com
Sat Nov 14 13:53:35 UTC 2020


I want to use [telnet library][1] to run some
commands on cisco switches and then parse output.
Thus, first i need to login (enter username and
password, etc) and then run commands and collect
output. As far as i understand that library API,
all of output parsing should be done in


of type

     TelnetPtr -> Event -> IO ()

But, these (mine) operations require some state
(to track where am i now (entered username,
entered password, etc) and to collect output). But
the monad of this event handler is IO, so i can't
see any simple way of adding state to it apart
from ['unsafePerfromIO' trick][2], like

     telnetRef :: IORef TelnetRef
     {-# NOINLINE telnetRef #-}
     telnetRef   = unsafePerformIO $ newIORef (TelnetRef undefined Unauth M.empty)

('undefined' is 'Telnet' pointer, which is
returned by 'telnetInit' and will be initialized

Is there a better a way to do this?


[1]: https://hackage.haskell.org/package/libtelnet
[2]: https://wiki.haskell.org/Top_level_mutable_state

More information about the Beginners mailing list