Skip to content

Instantly share code, notes, and snippets.

@anthonyjb
Last active December 7, 2017 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyjb/d816e50dbd7e936ec2103576b2d7d72a to your computer and use it in GitHub Desktop.
Save anthonyjb/d816e50dbd7e936ec2103576b2d7d72a to your computer and use it in GitHub Desktop.
# Prerequisites:
#
# - Using Python 3.5+
# - Install manhattan-chains (`pip install manhattan-chains`)
#
from manhattan.chains import Chain
# Define the chains
# Show the list
show = Chain([
'get_list',
'render_list'
])
@show.link
def get_list(state):
if state.args[0] not in state.lists:
return 'List not found: ' + state.args[0]
state.list_name = state.args[0]
state.list = state.lists[state.list_name]
@show.link
def render_list(state):
lines = [state.list_name, '-' * len(state.list_name)]
lines += ['- ' + item for item in state.list]
return '\n' + '\n'.join(lines) + '\n'
# Add an item to the list
add = Chain([
'get_list',
'add_item',
'render_list'
])
add.set_link(get_list)
add.set_link(render_list)
@add.link
def add_item(state):
state.list.append(state.args[1])
# Add a new list
new = Chain([
'is_name_unique',
[
[
'add_list',
'render_list'
],
[
'make_name_unique',
'add_list',
'render_list'
]
]
])
new.set_link(render_list)
@new.link
def is_name_unique(state):
state.list_name = state.args[0]
return state.list_name not in state.lists
@new.link
def add_list(state):
state.lists[state.list_name] = []
state.list = state.lists[state.list_name]
@new.link
def make_name_unique(state):
i = 1
while state.list_name in state.lists:
state.list_name = '{0}-{1}'.format(state.list_name, i)
# Define a table of lists
lists = {
'shopping': ['milk', 'eggs'],
'todo': ['take dog to groomers']
}
# Define a table of actions the user can perform
actions = {
'add': add,
'new': new,
'show': show
}
# Parse the users commands
while True:
user_input = input('? ')
[action, *args] = user_input.split(' ')
if action == 'quit':
break
elif action in actions:
output = actions[action](lists=lists, args=args)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment