Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 559
Bigba Mbum Avatar asked Aug 08 '26 00:08

Bigba Mbum


2 Answers

Let's assume, you have that pair of integers as state:

f = do put (1,2)
       modify (\(x,y) -> (x*y,y))
       modify (\(x,y) -> (x,y+x))

Is that, what you want?

like image 142
fuz Avatar answered Aug 09 '26 14:08

fuz


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
like image 32
Mikhail Glushenkov Avatar answered Aug 09 '26 15:08

Mikhail Glushenkov



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!