A brutalized Haskell programmer
In working on a special Xmas lecture for my 1st semester course, I was going through Fritz Ruehr's "The Evolution of a Haskell Programmer" only to notice that there is no imperatively faked version that uses references. This omission could be resolved with the following code:
For instance:
module Control.Pascal where
import Data.IORef
while :: IORef a -> (a -> Bool) -> IO () -> IO ()
while ref pred body = while'
where
while' = do
v <- readIORef ref
if (pred v)
then body >> while'
else return ()
{- ******************************* -}
import Data.IORef
import Control.Pascal
factorial n
= do
r <- newIORef 1
i <- newIORef n
while i (>0) (
readIORef i >>=
modifyIORef r . (*) >>
modifyIORef i ((+) (-1))
)
readIORef r
For instance:
Prelude> factorial 5
120
Comments
Post a Comment