Just Haskell being better than Java at being Java
| import Control.Monad | |
| import Control.Monad.ST | |
| import Data.STRef | |
| import Data.Maybe | |
| data Iterator s a = | |
| Iterator { | |
| next :: | |
| ST s (Maybe a) | |
| , hasNext :: | |
| ST s Bool | |
| } | |
| -- [1,3,5,7,9] | |
| from1to9by2 :: | |
| Iterator s Int | |
| from1to9by2 = | |
| let current = newSTRef (Just 1) | |
| in Iterator { | |
| next = | |
| do c <- current | |
| r <- readSTRef c | |
| modifySTRef c (>>= \n' -> if n' == 9 then Nothing else Just n') | |
| return r | |
| , hasNext = | |
| do c <- current | |
| r <- readSTRef c | |
| return (isNothing r) | |
| } | |
| while :: | |
| Monad m => | |
| m Bool | |
| -> m a | |
| -> m () | |
| while p a = | |
| do q <- p | |
| when q (a >> while p a) | |
| whileHasNext :: | |
| Iterator s a | |
| -> (a -> ST s a) | |
| -> ST s () | |
| whileHasNext i k = | |
| while | |
| (hasNext i) | |
| (next i >>= k . fromMaybe (error "lol: scru u, no correct programs 4 u.")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment