Rev | Line | |
---|
[19] | 1 | {-# LANGUAGE FlexibleContexts,FlexibleInstances #-} |
---|
| 2 | module Lambda where |
---|
| 3 | |
---|
| 4 | import qualified Data.Supply as S |
---|
| 5 | import qualified Data.Char as C |
---|
| 6 | |
---|
| 7 | {- |
---|
| 8 | - Lambda calculus beagyazas |
---|
| 9 | -} |
---|
| 10 | class Lambda l where |
---|
| 11 | lam :: (l a -> l b) -> l (a -> b) |
---|
| 12 | app :: l (a -> b) -> l a -> l b |
---|
| 13 | const :: Int -> l Int |
---|
| 14 | |
---|
| 15 | {- |
---|
| 16 | - eval interpreter |
---|
| 17 | -} |
---|
| 18 | newtype Q a = Q { unQ :: a } |
---|
| 19 | instance Lambda Q where |
---|
| 20 | const = Q |
---|
| 21 | lam a = Q (unQ.a.Q) |
---|
[20] | 22 | app a b = Q $ unQ a (unQ b) |
---|
[19] | 23 | |
---|
[20] | 24 | eval :: Q a -> a |
---|
[19] | 25 | eval = unQ |
---|
| 26 | |
---|
| 27 | {- |
---|
| 28 | - show interpreter |
---|
| 29 | -} |
---|
[20] | 30 | showVar :: Int -> String -> String |
---|
[19] | 31 | showVar x = if x>28 |
---|
| 32 | then showVar (x `div` 29) . showChar (C.chr $ C.ord 'a' + (x `mod` 29)) |
---|
| 33 | else showChar $ C.chr $ C.ord 'a' + x |
---|
| 34 | |
---|
[20] | 35 | -- unS :: Value supply -> Precedence -> ShowS |
---|
[19] | 36 | newtype S a = S { unS :: S.Supply Int -> Int -> ShowS } |
---|
[20] | 37 | |
---|
[19] | 38 | instance Lambda S where |
---|
[20] | 39 | const a = S (\_ p -> showsPrec p a) |
---|
[19] | 40 | app (S fun) (S arg) = S (\s p -> |
---|
| 41 | let (s1, s2) = S.split2 s |
---|
| 42 | in showParen (p>6) $ fun s1 6 . showChar ' ' . arg s2 7) |
---|
| 43 | lam fun = S (\s p -> |
---|
| 44 | let (s1, s2) = S.split2 s |
---|
| 45 | v = S.supplyValue s1 |
---|
| 46 | showV = S $ \_ _ -> showVar v |
---|
| 47 | in showParen (p>0) $ showChar 'λ' . showVar v . showChar '.' . unS (fun showV) s2 0) |
---|
| 48 | |
---|
[20] | 49 | ast :: S a -> IO ShowS |
---|
[19] | 50 | ast a = do |
---|
| 51 | s <- S.newSupply 0 (+1) |
---|
| 52 | return $ unS a s 0 |
---|
| 53 | |
---|
[20] | 54 | printAst :: S a -> IO () |
---|
| 55 | printAst l = ast l >>= (\s -> putStrLn $ s "") |
---|
Note: See
TracBrowser
for help on using the repository browser.