Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Change state in IO function

I'm trying to update a record in an IO-function. I have tried to use the state-monad without success. I saw a comment somewhere that it was possible to solve a similar problem with the state-monad. Is it possible to use the State-monad to do this or do I have to use a monad transformer? If so I would be grateful for a short explanation on how to do it.

{-# LANGUAGE GADTs #-}

data CarState = CS {color :: String  }

initState :: CarState
initState = CS {color = "white"}


data Car where
   ChangeColor :: String  -> Car

func :: Car -> CarState -> IO ()
func (ChangeColor col) cs = do

     putStrLn ("car is " ++ show(color cs))

     -- Change state here somehow
    --  colorChange "green"

     putStrLn ("car is now" ++ show(color cs))


main :: IO ()
main = func (ChangeColor "green") initState 

colorChange :: String -> MyState CarState String
colorChange col = do
     cs <- get
     put $ cs {color = col}
     return col


data MyState s a = St (s -> (a,s)) 

runSt :: MyState s a -> s -> (a,s)
runSt (St f) s = f s 

evalSt :: MyState s a -> s -> a
evalSt act = fst . runSt act 

get :: MyState s s
get = St $ \s -> (s,s)

put :: s -> MyState s ()
put s = St $ \_ -> ((),s)

instance Monad (MyState s) where
   return x       = St $ \s -> (x,s) 
   (St m) >>= k = St $ \s_1 -> let (a, s_2) = m s_1
                               St k_m = k a 
                           in k_m s_2 

instance Functor (MyState s) where
    fmap f (St g) = St $ \s0 -> let (a, s1) = g s0
                                in (f a, s1)

instance Applicative (MyState s) where
    pure a = St (\s -> (a,s))
    (<*>) (St sa) (St sb) = St (\s0 -> let (fn, s1) = sa s0 
                                       (a,  s2) = sb s1  
                                   in (fn a, s2))
like image 999
datamoose Avatar asked Mar 30 '26 21:03

datamoose


1 Answers

In Haskell you cannot mutate data in place, ever, by any mechanism. At all.1

The way state updates are modeled in Haskell is by producing a new value, which is identical to the old value, except for the "updated" bit.

For example, what you're trying to do would be expressed like this:

func :: Car -> CarState -> CarState
func (ChangeColor c) cs = cs { color = c }

1 Well, ok, technically you can sometimes, but it only works for data that has been arranged in advance to be mutable, and it is usually quite cumbersome. Not a normal way to write programs.

like image 171
Fyodor Soikin Avatar answered Apr 02 '26 21:04

Fyodor Soikin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!