X-Git-Url: http://git.tomasm.cz/fp.git/blobdiff_plain/494e6afee1f1c583a880fca4e1f234de6823271a..d276bbe5bee77bc96200366978c283993b8154c8:/src/Lambda.hs?ds=sidebyside diff --git a/src/Lambda.hs b/src/Lambda.hs index 54c4065..c570199 100644 --- a/src/Lambda.hs +++ b/src/Lambda.hs @@ -1,20 +1,65 @@ {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} - -module Lambda where +{-# LANGUAGE PatternSynonyms #-} + +-- | +-- Module : Lambda +-- Copyright : Tomáš Musil 2014 +-- License : BSD-3 +-- +-- Maintainer : tomik.musil@gmail.com +-- Stability : experimental +-- +-- This is a toy λ-calculus implementation. + +module Lambda + ( -- * Types + VarName + , Term(..) + -- * Parsing terms + , parseTerm + , tRead + -- * Reduction + , reduce + ) where + import Data.Text as T import Data.Attoparsec.Text import Control.Applicative +-- $setup +-- >>> import Test.QuickCheck +-- >>> import Control.Applicative +-- >>> let aTerm 0 = pure $ Var "x" +-- >>> let aTerm n = oneof [pure (Var "x"), liftA (Lambda "x") $ aTerm (n - 1), liftA2 App (aTerm (n `div` 2)) (aTerm (n `div` 2))] +-- >>> instance Arbitrary Term where arbitrary = sized aTerm + type VarName = String -data Term = Var VarName | Lambda VarName Term | App Term Term + +-- | +-- >>> print $ Lambda "x" (Var "x") +-- (λx.x) + +data Term = Var VarName | Lambda VarName Term | App Term Term deriving (Eq) + +-- 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) + instance Show Term where show (Var x) = x - show (Lambda x t) = "\\" ++ x ++ "." ++ show t - show (App t r) = "(" ++ show t ++ " " ++ show r ++ ")" + show (EmLambda x y t) = show (Lambda (x ++ " " ++ y) t) + show (Lambda x t) = "(λ" ++ x ++ "." ++ show t ++ ")" + show (AppApp a b c) = show a ++ " " ++ braced (App b c) + show (App t r) = show t ++ " " ++ show r + +braced :: Term -> String +braced t = "(" ++ show t ++ ")" + +-- | +-- prop> t == tRead (show (t :: Term)) ---instance Read Term where tRead :: String -> Term tRead s = case parseOnly (parseTerm <* endOfInput) (T.pack s) of (Right t) -> t @@ -27,7 +72,7 @@ parseVar = do parseLambda :: Parser Term parseLambda = do - char '\\' + char '\\' <|> char 'λ' vars <- sepBy1 parseVar (char ' ') char '.' t <- parseTerm