I have the following algebraic data type representing the Lambda Calculus in Haskell:
data LExpr
= Var String -- variable
| App LExpr LExpr -- function application
| Lam String LExpr -- Lambda abstraction
deriving (Eq, Show)
I am trying to build the accompanying fold function. I am acquainted with the general fold form for algebraic data types, which can be in such way present:
foldr :: (α -> β-> β) -> β -> [α] -> β
foldr (#) z = go
where
go [] = z
go (x:xs) = x # go xs
So, what I have done so far:
lfold :: (String -> a) -> (a -> a -> a) -> (String -> a -> a) -> LExpr -> a --given by definition
lfold f z = go
where
go (Var _) = z --Not sure here how to do the base case
go (Lam v e) = v f go e
Is this the correct way? If not, where I am wrong and how to fix it?
I will only provide a hint.
Suppose you have a list of integers type as follows:
Then, the fold becomes
Notice that, once I carefully name the arguments
nil, cons
then it's just a matter of 1) mappingNil
(constructor) tonil
(parameter), 2) mappingCons
tocons
, 3) applyinggo
to subterms of typeList
(i.e.,xs
).For your type,
we can use the same trick:
Notice how I named the three arguments:
var, app, lam
. By checking what happened in theList
type above, you should now be able to fill in the blanks.