-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPrimitives.hs
More file actions
42 lines (32 loc) · 1.19 KB
/
Copy pathPrimitives.hs
File metadata and controls
42 lines (32 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module Primitives where
import Control.Monad.Error
import Control.Monad.State
import Control.Monad.IO.Class
import System.Exit
import Forth
primitives :: [(String, Forth ())]
primitives = [ ("+", binaryOp (+))
, ("-", binaryOp (-))
, ("*", binaryOp (*))
, ("/", binaryOp div)
, ("=", comparisonOp (==))
, ("BYE", liftIO exitSuccess)
, (".", liftIO . print =<< pop)
, (".S", liftIO . print . stack =<< get)
, ("IF", throwError "Interpreting a compile-only word")
, ("ELSE", throwError "Interpreting a compile-only word")
, ("THEN", throwError "Interpreting a compile-only word")
, (";", throwError "Interpreting a compile-only word")
, (":", beginCompile)
]
binaryOp :: (Val -> Val -> Val) -> Forth ()
binaryOp f = do
x <- pop
y <- pop
push (f y x)
comparisonOp :: (Val -> Val -> Bool) -> Forth ()
comparisonOp f = binaryOp $ \x y -> (toInteger . fromEnum) (f x y)
beginCompile :: Forth ()
beginCompile = get >>= \vm -> case (mode vm) of
Interpret -> put vm { mode = Compile }
_ -> throwError "Illegal use of :"