+
+data Strategy = Eager | Lazy
+
+reduceStep :: (Monad m) => Term -> m Term
+reduceStep (RedEx x s t) = return $ substitute x t s
+reduceStep t = return $ t
+
+data Z = R Term Z | L Z Term | ZL VarName Z | E
+data D = Up | Down
+type TermZipper = (Term, Z, D)
+
+move :: TermZipper -> TermZipper
+move (App l r, c, Down) = (l, L c r, Down)
+move (Lambda x t, c, Down) = (t, ZL x c, Down)
+move (Var x, c, Down) = (Var x, c, Up)
+move (t, L c r, Up) = (r, R t c, Down)
+move (t, R l c, Up) = (App l t, c, Up)
+move (t, ZL x c, Up) = (Lambda x t, c, Up)
+move (t, E, Up) = (t, E, Up)
+
+unmove :: TermZipper -> TermZipper
+unmove (t, L c r, Down) = (App t r, c, Down)
+unmove x = x
+
+travPost :: (Monad m) => (Term -> m Term) -> Term -> m Term
+travPost fnc term = tr fnc (term, E, Down)
+ where
+ tr f (t@(RedEx _ _ _), c, Up) = do
+ nt <- f t
+ tr f $ (nt, c, Down)
+ tr _ (t, E, Up) = return t
+ tr f (t, c, Up) = tr f $ move (t, c, Up)
+ tr f (t, c, Down) = tr f $ move (t, c, Down)
+
+travPre :: (Monad m) => (Term -> m Term) -> Term -> m Term
+travPre fnc term = tr fnc (term, E, Down)
+ where
+ tr f (t@(RedEx _ _ _), c, Down) = do
+ nt <- f t
+ tr f $ unmove (nt, c, Down)
+ tr _ (t, E, Up) = return t
+ tr f (t, c, Up) = tr f $ move (t, c, Up)
+ tr f (t, c, Down) = tr f $ move (t, c, Down)
+
+printT :: Term -> IO Term
+printT t = do
+ print t
+ return t
+
+-- |
+--
+-- >>> toNormalForm Eager 100 cI
+-- Just (λx.x)
+--
+-- >>> toNormalForm Eager 100 $ App cI cI
+-- Just (λx.x)
+--
+-- >>> toNormalForm Eager 100 $ (App (App cK cI) cY)
+-- Nothing
+--
+-- >>> toNormalForm Lazy 100 $ (App (App cK cI) cY)
+-- Just (λx.x)
+--
+-- prop> (\ t u -> t == u || t == Nothing || u == Nothing) (alphaNorm <$> toNormalForm Lazy 1000 x) (alphaNorm <$> toNormalForm Eager 1000 x)
+
+
+toNormalForm :: Strategy -> Int -> Term -> Maybe Term
+toNormalForm Eager n = flip evalStateT 0 . travPost (cnt >=> short n >=> reduceStep)
+toNormalForm Lazy n = flip evalStateT 0 . travPre (cnt >=> short n >=> reduceStep)
+
+cnt :: (Monad m) => Term -> StateT Int m Term
+cnt t@(RedEx _ _ _) = do
+ modify (+ 1)
+ return t
+cnt t = return t
+
+short :: Int -> Term -> StateT Int Maybe Term
+short maxN t = do
+ n <- get
+ if n > maxN
+ then lift Nothing
+ else return t