zhaw-fup/Exercises/exercise-7/Lambda.hs

90 lines
1.9 KiB
Haskell
Raw Normal View History

2024-06-16 22:36:43 +00:00
import Data.Set (Set, empty, delete, union, singleton)
2024-06-16 22:02:00 +00:00
--------------------
-- Slides
--------------------
2024-06-16 22:01:19 +00:00
data Term =
Nat Integer
| Abs String Term -- EAbs Abstraction
| Inv Term Term -- EApp Invocation (a.k.a. Application) of a function
| Var String -- EVar a variable
| Add
2024-06-16 22:02:00 +00:00
pretty x = case x of
2024-06-16 22:31:18 +00:00
(Abs param term) -> "L" ++ param ++ "." ++ pretty term
2024-06-16 22:02:00 +00:00
(Inv func param) -> "(" ++ pretty func ++ " " ++ pretty param ++ ")"
(Var name) -> name
Add -> "Add"
2024-06-16 22:26:34 +00:00
Nat value -> show value
2024-06-16 22:02:00 +00:00
-- example
-- >>> pretty (Abs "x" $ Abs "y" $ Inv (Inv Add (Var "x")) (Var "y"))
-- "Lx.Ly.((Add x) y)"
2024-06-16 22:36:43 +00:00
freeVars :: Term -> Set String
freeVars x = case x of
(Abs param term) -> delete param (freeVars term)
(Inv func param) -> freeVars func `union` freeVars param
(Var name) -> singleton name
_ -> empty
-- example
-- >>> freeVars (Inv (Var "y") $ Abs "x" Add)
-- fromList ["y"]
2024-06-16 22:02:00 +00:00
2024-06-16 21:49:48 +00:00
--------------------
-- Exercise 1
--------------------
-- Ja
-- Nein
-- Ja
-- Nein
2024-06-16 21:59:43 +00:00
--------------------
-- Exercise 2
--------------------
2024-06-16 22:23:26 +00:00
-- Rule 1: Function bodies in (L{param}.{body}) span as much as possible:
-- Lx.A B C == Lx.(A B C)
-- Rule 2: Function invocations (application) are left bound
-- A B C == ((A B) C)
2024-06-16 21:59:43 +00:00
-- ((Lx.(x z)) (Ly.(x y)))
-- ((Lx.(x z)) (Ly.(w (Lw.(((w y) z) x)))))
-- (Lx.((x y) (Lx.(y x))))
2024-06-16 22:07:02 +00:00
--------------------
-- Exercise 3
--------------------
-- (Lx.((x *z*) (Ly.(x y))))
-- ((Lx.(x *z*)) Ly.(*w* (Lw.(((w y) *z*) *x*))))
-- Lx.((x "y") (Lx.("y" x)))
2024-06-16 22:20:32 +00:00
--------------------
-- Exercise 4
--------------------
----------
-- 1.)
----------
-- (((Lz.z) (Ly.yy)) (Lx.xa))
-- ((Ly.yy) (Lx.xa))
-- (Lx.xa (Lx.xa))
-- (Lx.xa) a
-- (a a)
----------
-- 2.)
----------
-- (Lx.(x x))(Ly.(y x)) z
-- (Ly.(y x)) (Ly.(y x)) z
-- ((Ly.(y x)) x) z
-- (x x) z
-- x x z
----------
-- 3.)
----------
-- ((Lx.(x x))(Ly.y))(Ly.y)
-- ((Ly.y Ly.y))(Ly.y)
-- (Ly.y)(Ly.y)
-- (Ly.y)