summaryrefslogtreecommitdiff
path: root/src/Unlambda/Interpreter.hs
blob: f1dcf05db22317300903553a08f71b55604f9159 (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
module Unlambda.Interpreter (
    unlambda
    ) where


import System.IO.Error
import Control.Monad.Trans.Cont
import Control.Monad.IO.Class
import Data.Maybe
import Unlambda.Parser
import Unlambda.Types




unlambda :: UnlambdaTerm -> IO UnlambdaTerm
unlambda term = getResult $ eval term



eval :: UnlambdaTerm -> ULM UnlambdaTerm
eval term =
    case term of
        App f x -> do
            t <- eval f
            apply t x
        _ -> return term



apply :: UnlambdaTerm -> UnlambdaTerm -> ULM UnlambdaTerm
apply firstTerm secondTerm =
    case firstTerm of
        K -> eval secondTerm >>= return . Kpartial

        Kpartial x -> eval secondTerm >> return x

        S -> eval secondTerm >>= return . Spartial

        Spartial x -> eval secondTerm >>= return . (Sapp x)

        Sapp x y -> do
            z <- eval secondTerm
            eval (App (App x z) (App y z))

        I -> eval secondTerm

        V -> eval secondTerm >> return V

        C -> callCC $ \cont -> eval (App secondTerm (Continuation cont))

        Continuation cont -> eval secondTerm >>= cont

        D -> return (Promise secondTerm)

        Promise x -> eval secondTerm >>= eval . (App x)

        Dot c -> do
            t <- eval secondTerm
            liftIO (putChar c)
            return t

        R -> do
            t <- eval secondTerm
            liftIO (putChar '\n')
            return t

        E -> eval secondTerm >>= doExit

        Reed -> do
            t <- eval secondTerm
            ch <- liftIO (catchIOError (getChar >>= return . Just) (\e -> return Nothing))
            setCurChar ch
            if (isNothing ch) then eval (App t V) else eval (App t I)

        Bar -> do
            t <- eval secondTerm
            ch <- getCurChar
            if (isNothing ch) then eval (App t V) else eval (App t I)

        Compare c -> do
            t <- eval secondTerm
            ch <- getCurChar
            if (ch /= Just c) then eval (App t V) else eval (App t I)