I am trying to understand the monad system in Haskell. About 80% of my previous programming experience is in C, but, ironically, the urgent part of Haskell is the hardest to understand. Enumerating the manipulations and lazy assessment was much clearer. Anyway, I want ghc to accept this code. I know the code does not make sense. Most obviously, I pass Bool where IO Bool is expected. But this is not the only problem. I know this is a stupid question, but please help me understand my understanding of the Haskell language.
import Control.Monad while :: Monad m => m Bool -> m () -> m () while cond action = do c <- cond when c $ do action while cond action main :: IO () main = do i <- 0 while (i < 10) $ do i <- i + 1 print i
This is how I finally did it. I know that allocaArray not needed, but it was a lot of fun to use. Haskell really has no boundaries, very powerful.
import Control.Monad import Data.IORef import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Array while :: Monad m => m Bool -> m () -> m () while cond action = do c <- cond if c then do action while cond action else return () main :: IO () main = do let n = 10 allocaArray n $ \p -> do i <- newIORef 0 while (liftM (< n) (readIORef i)) $ do i2 <- readIORef i poke (advancePtr p i2) i2 modifyIORef i (+ 1) writeIORef i 0 while (liftM (< n) (readIORef i)) $ do i2 <- readIORef i (peek $ advancePtr p i2) >>= print modifyIORef i (+ 1)
source share