6

I wanted to be able to formulate the hindley-milner type inference algorithm using fix-point data types and recursion schemes. Disregarding all detail apart from the actual recursion parts:

w env term = case term of 
    Lam n e -> lam (w (modify1 env) e)
    App a b -> app (w (modify2 env) a) (w (modify3 env) b)
    ...

The algorithm builds an environment data structure env as it recursively traverses the tree until it reaches the leafs. Then it uses this information as it builds up the result again.

Without the env part, this could be easily implemented with cata. Can this (with env) be done in general using recursion schemes?

4
  • 1
    Yes just make the target of the cata a function Env -> a Commented Sep 8, 2017 at 23:55
  • 1
    Yes, but you'll probably need to use cata with a higher-order carrier type, computing an action that can modify the environment and possibly fail. Commented Sep 8, 2017 at 23:55
  • Got it. Genius. Thanks Commented Sep 9, 2017 at 0:10
  • 1
    @user47376 something about it feels a bit magical, doesn't it? Commented Sep 9, 2017 at 1:52

2 Answers 2

3

Without the env part, this could be easily implemented with cata. Can this (with env) be done in general using recursion schemes?

What you're looking for is a chronomorphism. This allows you to do recursion using both results from the future and the past. It's not quite as user-friendly as it sounds, but it is the canonical way of doing things using recursion schemes.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes just make the target of the cata a function Env -> a

– luqui

Yes, but you'll probably need to use cata with a higher-order carrier type, computing an action that can modify the environment and possibly fail.

– pigworker

1 Comment

Now write algorithm W as a tail-recursive traversal using the same data structure as both the zipper and the environment of unification variables. You'll be glad you did.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.