Call-Site Code Replacement in Functional Programming Languages

functional-programming, haskell

Solution

That's basically the automaton arrow:

newtype Auto a b = Auto (a -> (b, Auto a b))

In Haskell it's not possible for a function to replace itself, but the automaton arrow represents functions that return a new version of themselves along with a result:

switcher :: Bool -> Auto Bool Bool
switcher x =
    Auto $ \y ->
        (x, switcher $ if y then not x else x)

The useful thing about the automaton arrow is that it is, well, an arrow, so the `Category` instance allows you to compose such functions. There is also a very useful applicative instance.

Side note: This is the basis of arrowized functional reactive programming (AFRP).

Problem

I just wonder whether it is possible in a functional language to do call site replacement. I envision this as a special form of lazyness. Basically I would call somewhere a function f with an argument a: ``` ... (f a) ... ``` The function would then manage to replace itself by a function g with an argument b: ``` ... (g b) ... ``` So that the next time the original call site of (f a) is invoked in fact (g b) is invoked. Hints welcome. Bye P.S.: Its for Just-In-Time (JIT) compilation. Polymorphic inline caches and the like. See for example: Optimizing Dynamically - Typed Object - Oriented Languages with Polymorphic Inline Caches Urs Hölzle, Craig Chambers, David Ungar ECOOP '91 Proceedings of the European Conference on Object-Oriented Programming http://selflanguage.org/_static/published/pics.pdf

Original source