Search code examples
chaskelltranslate

Translate C code into Haskell


How do I translate this portion of C code into Haskell? From what I know, I must use the State monad, but I don't know how.

int x = 1;
int y = 2;
x =  x * y;
y = y + x;

Solution

  • A literal translation would use IORefs:

    import Data.IORef
    
    main :: IO ()
    main = do x <- newIORef 1
              y <- newIORef 2
              y_val <- readIORef y
              modifyIORef x (\v -> v * y_val)
              x_val <- readIORef x
              modifyIORef y (\v -> v + x_val)
    

    As you can see, imperative programming is ugly in Haskell. This is intentional, to coax you into using functional style. You can define some helper functions, though, to make this more bearable:

    import Data.IORef
    
    -- x := f x y
    combineToR :: (a -> t -> a) -> IORef a -> IORef t -> IO ()
    combineToR f x y = do y_val <- readIORef y
                          modifyIORef x (\v -> f v y_val)
    
    addTo :: Num a => IORef a -> IORef a -> IO ()
    addTo = combineToR (+)
    
    multWith :: Num a => IORef a -> IORef a -> IO ()
    multWith = combineToR (*)
    
    main :: IO ()
    main = do x <- newIORef 1
              y <- newIORef 2
              multWith x y
              addTo y x