basic substitution implemented

This commit is contained in:
jingus 2026-05-15 19:00:37 -05:00
parent f64bf8be2b
commit fee6a0e4a3
2 changed files with 27 additions and 4 deletions

View file

@ -1,6 +1,18 @@
module Evaluation where module Evaluation where
import Parser (Expr (Variable)) import Parser (Expr (Abstraction, Application, Variable))
-- | substitute all variables matching string in first expression with second expression
subst :: Expr -> String -> Expr -> Expr
subst v@(Variable vname) name content = if vname == name then content else v
subst (Abstraction vname body) name content = Abstraction vname (subst body name content)
subst (Application f arg) name content = Application (subst f name content) (subst arg name content)
bind :: Expr -> Expr -> Either String Expr
bind (Abstraction v b) arg = Left "Unimplemented"
beta :: Expr -> Maybe Expr
beta _ = Nothing
run :: Expr -> Expr run :: Expr -> Expr
run _ = Variable "a" run _ = Variable "a"

View file

@ -1,8 +1,19 @@
module EvaluationSpec (spec) where module EvaluationSpec (spec) where
import Evaluation (subst)
import Parser (Expr (Abstraction, Application, Variable))
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
spec = do spec = do
describe "Evaluation" $ do describe "subst" $ do
it "can evaluation expressions" $ it "cannot substitute mismatched variables" $
True `shouldBe` True subst (Variable "x") "y" (Variable "z") `shouldBe` Variable "x"
it "can substitute matched variables" $
subst (Variable "x") "x" (Variable "z") `shouldBe` Variable "z"
it "can substitute nested variables" $
subst absWithZ "z" absI `shouldNotBe` absWithZMaker absI
where
absWithZMaker z = Abstraction "x" (Application z (Variable "x"))
absWithZ = absWithZMaker (Variable "z")
absI = Abstraction "i" (Variable "i")