Skip to content

Instantly share code, notes, and snippets.

@NoahTheDuke
Last active September 10, 2015 18:23
Show Gist options
  • Save NoahTheDuke/eb26cc7b239380b8a906 to your computer and use it in GitHub Desktop.
Save NoahTheDuke/eb26cc7b239380b8a906 to your computer and use it in GitHub Desktop.
# Inspiration from [http://danthedev.com/2015/09/09/lisp-in-your-language/]
# Let's see what we can do in Python, eh?
# Lisp data structures:
# * Use ( and ) to denote lists
# * Arguments are space separated
# * First item is a function
# * Remaining items are the arguments
native = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
'=': lambda a, b: a == b,
'def': lambda a, b: pl_def(a, b),
'print': lambda *a: print(''.join(str(x) for x in a)) }
global scope_dict
scope_dict = {}
def pl_def(name, value):
global scope_dict
scope_dict[name] = value
return scope_dict[name]
def pl_eval(rawExpr):
# if the expression isn't a list, return it
if not isinstance(rawExpr, list):
return rawExpr
# use existing scope
global scope_dict
scope = scope_dict
# resolve all our new string names from our scope
def symbol_check(symbol):
if isinstance(symbol, list):
return symbol
elif symbol in scope:
return scope[symbol]
else:
return symbol
expression = [symbol_check(x) for x in rawExpr]
# the first item is the function or its name
fn_name = expression[0]
# resolve the function from native if necessary
fn = native[fn_name] if type(fn_name) == str else fn_name
# the remaining items are the arguments
def apply_func(arg):
# if this argument is an expression, treat it as code
if isinstance(arg, list):
return pl_eval(arg)
else:
return arg
args = [apply_func(x) for x in expression[1:]]
# call the function with these arguments
return fn(*args)
pl_eval(['print', "Hello world!\n", "Nailed it."])
#a = pl_eval([int, 4.14])
#b = pl_eval([print, [input, "What is your name?\n> "]])
#c = pl_eval(['=', 6, 6])
#d = pl_eval(['def', 'a', 5])
#e = pl_eval(['print', ['+', 'a', 'a']])
f = pl_eval(['print', ['def', 'a', 5]])
print(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment