Instance of Show for lambda-abstraction ADT

353 views Asked by At

So, I have already defined the lambda data type as such:

data LExpr
    = Variable String         -- variable
    | Apply LExpr LExpr       -- function application
    | Lambda String LExpr     -- Lambda abstraction 
    deriving (Eq, Show)  

Now I want to implement an instance of Show myself. I have already the function show' which does most of the work, but without using instances:

 show' :: LExpr -> String
 show' (Variable a) = a
 show' (Apply e1 e2) = "(" ++ show' e1 ++ " " ++ show' e2 ++ ")"                   
 show' (Lambda x e) = "(λ " ++ x ++ ". " ++ show' e ++ ")"    

How I can implement it, to get the following output without using explicitly the show' function:

Main> (Apply (Lambda "x" (Apply (Variable "x") (Variable "y"))) (Variable "z"))
((λ x. x y) y)       
1

There are 1 answers

0
Alec On BEST ANSWER

Add an instance declaration for the Show class.

instance Show LExpr where
  show = show'

And remove the deriving(Show) part

data LExpr
    = Variable String         -- variable
    | Apply LExpr LExpr       -- function application
    | Lambda String LExpr     -- Lambda abstraction 
    deriving (Eq)