gcs function using a while loop in haskell
| import Control.Monad | |
| import Control.Monad.ST | |
| import Data.STRef | |
| gcd :: | |
| Integer | |
| -> Integer | |
| -> Integer | |
| gcd a b = | |
| runST $ | |
| do a' <- newSTRef a | |
| b' <- newSTRef b | |
| while ((/= 0) . snd) | |
| (a' `read2` b') | |
| (\(x, y) -> | |
| b' |= (x `mod` y) >> | |
| a' |= y) | |
| fst | |
| -- BEGIN peripherals | |
| read2 :: | |
| STRef s a | |
| -> STRef s b | |
| -> ST s (a, b) | |
| read2 a b = | |
| liftM2 (,) (readSTRef a) (readSTRef b) | |
| while :: | |
| Monad m => | |
| (t -> Bool) | |
| -> m t | |
| -> (t -> m a) | |
| -> (t -> b) | |
| -> m b | |
| while p s z e = | |
| do a <- s | |
| z a | |
| b <- s | |
| if p b | |
| then while p s z e | |
| else return (e b) | |
| (|=) :: | |
| STRef s a | |
| -> a | |
| -> ST s () | |
| (|=) = | |
| writeSTRef |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment