Ver Código Fonte

Imperative programming in Haskell (sort of).

Lucas Stadler 13 anos atrás
pai
commit
e27f1d9dd2
1 arquivos alterados com 40 adições e 0 exclusões
  1. 40 0
      hs/ImperativeProgramming.hs

+ 40 - 0
hs/ImperativeProgramming.hs

@ -0,0 +1,40 @@
1
{-
2
 - Imperative programming in Haskell.
3
 -
4
 - Another monadic exercise.
5
 -}
6
module ImperativeProgramming where
7
8
import Data.Maybe (fromJust)
9
import qualified Data.Map as M
10
import Control.Monad (liftM)
11
import Control.Applicative ((<$>), (<*>))
12
13
example = do
14
    "x" .= 3
15
    "x" .+= 4
16
    "y" .= (-1)
17
    "x" .+ "y"
18
19
data Imperative a b = Imperative (M.Map String a -> (M.Map String a, b))
20
21
executeImperative env (Imperative program) = program env
22
23
instance Monad (Imperative a) where
24
    Imperative lastOperation >>= action = Imperative $ \env ->
25
        let (env', value) = lastOperation env
26
            (Imperative f) = action value
27
        in f env'
28
29
    return x = Imperative $ \env -> (env, x)
30
31
name .= value = Imperative $ \env -> (M.insert name value env, value)
32
name .+= value = Imperative $ \env ->
33
    (M.insertWith (+) name value env, value + (fromJust $M.lookup name env))
34
binaryOp op = \var1 var2 -> Imperative $ \env ->
35
    (env, fromJust $ op <$> M.lookup var1 env <*> M.lookup var2 env)
36
37
(.+) = binaryOp (+)
38
(.-) = binaryOp (-)
39
(.*) = binaryOp (*)
40
(./) = binaryOp (/)