Search code examples
pythonlanguage-agnostictype-theory

How to make these dynamically typed functions type-safe?


Is there any programming language (or type system) in which you could express the following Python-functions in a statically typed and type-safe way (without having to use casts, runtime-checks etc)?

#1:

# My function - What would its type be? 
def Apply(x):
    return x(x)

# Example usage
print Apply(lambda _: 42)

#2:

white = None
black = None

def White():
    for x in xrange(1, 10):
        print ("White move #%s" % x)
        yield black

def Black():
    for x in xrange(1, 10):
        print ("Black move #%s" % x)
        yield white

white = White()
black = Black()

# What would the type of the iterator objects be?
for it in white:
    it = it.next()

Solution

  • 1# This is not typeable with a finite type. This means that very few (if any) programming languages will be able to type this.

    However, as you have demonstrated, there is a specific type for x that allows the function to be typed:

    x :: t -> B
    

    Where B is some concrete type. This results in apply being typed as:

    apply :: (t -> B) -> B
    

    Note that Hindley-Milner will not derive this type.

    2# This is easy to represent in Haskell (left as an exercise to the reader...)