Skip to content

Instantly share code, notes, and snippets.

@marcusziade
Last active December 28, 2022 02:22
Show Gist options
  • Save marcusziade/5d9d5a89276425aad85809c6f7e308aa to your computer and use it in GitHub Desktop.
Save marcusziade/5d9d5a89276425aad85809c6f7e308aa to your computer and use it in GitHub Desktop.
implement hindley-milner by skynet
# Define a set of basic types
INTEGER = 'INTEGER'
BOOLEAN = 'BOOLEAN'
FUNCTION = 'FUNCTION'
# Define a class for type variables
class TypeVar:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
# Define a class for type constraints
class Constraint:
def __init__(self, left, right):
self.left = left
self.right = right
# Define a function for generating fresh type variables
def fresh_type_var(name_hint):
return TypeVar(name_hint)
# Define a function for inferring the types of expressions
def infer_type(expr, constraints):
if isinstance(expr, int):
return INTEGER, constraints
elif isinstance(expr, bool):
return BOOLEAN, constraints
elif isinstance(expr, Function):
arg_type = fresh_type_var('arg')
return_type = fresh_type_var('return')
constraints.append(Constraint(expr.arg_type, arg_type))
constraints.append(Constraint(expr.return_type, return_type))
return FUNCTION, constraints
else:
raise ValueError(f'Unrecognized expression {expr}')
# Define a function for solving type constraints
def solve(constraints):
substitution = {}
for constraint in constraints:
if isinstance(constraint.left, TypeVar) and constraint.left not in substitution:
substitution[constraint.left] = constraint.right
return substitution
# Define a class for functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment