toNormalForm Eager
authorTomáš Musil <tomik.musil@gmail.com>
Fri, 12 Dec 2014 08:51:12 +0000 (09:51 +0100)
committerTomáš Musil <tomik.musil@gmail.com>
Fri, 12 Dec 2014 08:51:12 +0000 (09:51 +0100)
fp.cabal
src/Lambda.hs

index 789b94c..8be11df 100644 (file)
--- a/fp.cabal
+++ b/fp.cabal
@@ -21,6 +21,7 @@ library
                      , text >=1.2 && <1.3
                      , attoparsec >=0.12 && <0.13
                      , containers
+                     , mtl
   hs-source-dirs:      src
   default-language:    Haskell2010
 
@@ -32,6 +33,7 @@ executable fp
                      , text >=1.2 && <1.3
                      , attoparsec >=0.12 && <0.13
                      , containers
+                     , mtl
   hs-source-dirs:      src
   default-language:    Haskell2010
 
index c570199..f89cc7e 100644 (file)
@@ -26,6 +26,7 @@ module Lambda
 import Data.Text as T
 import Data.Attoparsec.Text
 import Control.Applicative
+import Control.Monad.State 
 
 -- $setup
 -- >>> import Test.QuickCheck
@@ -42,7 +43,7 @@ type VarName = String
 
 data Term = Var VarName | Lambda VarName Term | App Term Term deriving (Eq)
 
--- pattern RedEx x t s = App (Lambda x t) s
+pattern RedEx x t s = App (Lambda x t) s
 pattern AppApp a b c = App a (App b c)
 pattern EmLambda x y t = Lambda x (Lambda y t)
 
@@ -127,9 +128,49 @@ substitute a b (Lambda x t)
   | otherwise = Lambda x (substitute a b t)
 substitute a b (App t u) = App (substitute a b t) (substitute a b u)
 
+-- | Reduce λ-term
+--
+-- >>> reduce $ tRead "(\\x.x x) (g f)"
+-- g f (g f)
+
 reduce :: Term -> Term
 reduce (Var x) = Var x
 reduce (Lambda x t) = Lambda x (reduce t)
 reduce (App t u) = app (reduce t) u
   where app (Lambda x v) w = reduce $ substitute x w v
         app a b = App a (reduce b)
+
+data Strategy = Eager | Lazy
+
+reduceStep :: (Monad m) => Term -> m Term
+reduceStep (RedEx x s t) = return $ substitute x t s
+reduceStep t = return $ t
+
+traversPost :: (Monad m) => (Term -> m Term) -> Term -> m Term
+traversPost f (App t u) = do
+  nt <- traversPost f t
+  nu <- traversPost f u
+  f (App nt nu)
+traversPost f (Lambda x t) = f . Lambda x =<< traversPost f t
+traversPost f (Var x) = f (Var x)
+
+printT :: Term -> IO Term
+printT t = do
+  print t
+  return t
+
+toNormalForm :: Strategy -> Int -> Term -> Maybe Term
+toNormalForm Eager n = flip evalStateT 0 . traversPost (short n >=> cnt >=> reduceStep)
+
+cnt :: (Monad m) => Term -> StateT Int m Term
+cnt t@(RedEx _ _ _) = do
+  modify (+ 1)
+  return t
+cnt t = return t
+
+short :: Int -> Term -> StateT Int Maybe Term
+short max t = do
+  n <- get
+  if n == max
+    then lift Nothing
+    else return t