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
0 comments:
Post a Comment