Skip to content

Instantly share code, notes, and snippets.

@ayu-mushi
Last active October 4, 2015 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayu-mushi/622771bc2bd48e008077 to your computer and use it in GitHub Desktop.
Save ayu-mushi/622771bc2bd48e008077 to your computer and use it in GitHub Desktop.
Sleep on Haste Haskell by Operational Monad
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving #-}
import Haste
import Haste.Foreign
import Control.Monad.Operational
import Control.Monad.IO.Class
import Control.Applicative
data SleepableIOF a where
Sleep :: Int -> SleepableIOF ()
LiftIO :: IO x -> SleepableIOF x
newtype SleepableIO a = SleepableIO { unSleepableIO :: Program SleepableIOF a } deriving (Monad, Applicative, Functor)
instance MonadIO SleepableIO where
liftIO = SleepableIO . singleton . LiftIO
sleep :: Int -> SleepableIO ()
sleep = SleepableIO . singleton . Sleep
runSleepableIO :: SleepableIO () -> IO ()
runSleepableIO (SleepableIO (Program (Pure ()))) = return ()
runSleepableIO (SleepableIO (Program (Free (CoYoneda k (Sleep n))))) = setTimeout n (runSleepableIO (SleepableIO $ Program $ k ()))
runSleepableIO (SleepableIO (Program (Free (CoYoneda k (LiftIO act))))) = act >>= (runSleepableIO . SleepableIO . Program . k)
main :: IO ()
main = runSleepableIO $ do
t <- liftIO $ ffi $ toJSString "Date.now"
sleep 1000
text <- liftIO $ do
alert "hay"
return "Yo"
t' <- liftIO $ ffi $ toJSString "Date.now"
sleep $ t' - t
alert $ (show $ t' - t) ++ ": " ++ text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment