简体   繁体   中英

Unable to get a fully complete beta reduction in Haskell

I'm currently trying to implement beta reduction in Haskell, and I'm having a small problem. I've managed to figure out the majority of it, however as it is now I'm getting one small error when I test and I can't figure out how to fix it.

The code uses a custom datatype, Term and a substitution function which I defined beforehand, both of these will be below.

--Term datatype
data Term = Variable Var | Lambda Var Term | Apply Term Term

--Substitution function
substitute :: Var -> Term -> Term -> Term
substitute x n (Variable m)
    |(m == x) = n
    |otherwise = (Variable m)
substitute x n (Lambda m y)
    |(m == x) = (Lambda m y)
    |otherwise = (Lambda z (substitute x n (rename m z y)))
    where z = fresh (merge(merge(used y) (used n)) ([x]))
substitute x n (Apply m y) = Apply (substitute x n m) (substitute x n y)

--Beta reduction
beta :: Term -> [Term]
beta (Variable x) = []
beta (Lambda x y) =  map (Lambda x) (beta y)
beta (Apply (Lambda x m) n) = [(substitute x n m)] ++ [(Apply (Lambda x n) m) | m <- beta m] ++ [(Apply (Lambda x z) m) | z <- beta n]
beta (Apply x y) = [Apply x' y | x' <- beta x] ++ (map (Apply x) (beta y))

The expected outcome is as follows:

*Main> Apply example (numeral 1)
(\a. \x. (\y. a) x b) (\f. \x. \f. x)
*Main> beta it
[\c. (\b. \f. \x. \f. x) c b,(\a. \x. a b) (\f. \x. f x)]

However this is my outcome:

*Main> Apply example (numeral 1)
(\a. \x. (\y. a) x b) (\f. \x. \f. x)
*Main> beta it
[\c. (\b. \f. \x. \f. x) c b,(\a. \f. \x. \f. x) (\x. a b)]

Any help would be much appreciated.

Think you've also got your church numeral encoded wrong, numeral 1 should return

\f. \x. fx

rather than

\f. \x. \f. x \f. \x. \f. x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM