Skip to content

Instantly share code, notes, and snippets.

@kkismd
Last active August 23, 2019 10:19
Show Gist options
  • Save kkismd/d2f1bd5f8ffb0c10fae7ecad65b4cb76 to your computer and use it in GitHub Desktop.
Save kkismd/d2f1bd5f8ffb0c10fae7ecad65b4cb76 to your computer and use it in GitHub Desktop.
from typing import Optional
def maybe(func):
def fn(*args, **kwargs):
try:
ret = func(*args, **kwargs)
if ret:
return [ret]
else:
return[]
except Exception:
return []
return fn
@maybe
def findUser(code: str) -> Optional[dict]:
users = [
{"id": 1, "code": 2012, "name": "yuzu"},
{"id": 2, "code": 3308, "name": "yui"},
]
for user in users:
if user["code"] == code:
return user
return None
@maybe
def findItem(userId: int) -> Optional[dict]:
items = [
{"userId": 1, "name": "keyboard"}
]
for item in items:
if item["userId"] == userId:
return item
return None
@maybe
def parseInt(input: str) -> Optional[int]:
return int(input)
if __name__ == '__main__':
kbd = [item["name"]
for code in parseInt("2012")
for yuzu in findUser(code)
for item in findItem(yuzu["id"])]
print(kbd) # => ['keyboard']
missing = [item["name"]
for code in parseInt("3308")
for yui in findUser(code)
for item in findItem(yui["id"])]
print(missing) # => []
what = [item["name"]
for code in parseInt("wxyz")
for who in findUser(code)
for item in findItem(who["id"])]
print(what) # => []
class MaybeIterator:
def __init__(self, value):
self.value = value
self.index = -1
def __next__(self):
self.index += 1
if self.index == 0 and self.value:
return self.value
else:
raise StopIteration
class Maybe:
def __init__(self, value):
self.value = value
def __iter__(self):
return MaybeIterator(self.value)
def getOrElse(self, other):
if self.value:
return self.value
else:
return other
def findUser(code: str) -> Maybe:
users = [
{"id": 1, "code": 2012, "name": "yuzu"},
{"id": 2, "code": 3308, "name": "yui"},
]
for user in users:
if user["code"] == code:
return Maybe(user)
return Maybe(None)
def findItem(userId: int) -> Maybe:
items = [
{"userId": 1, "name": "keyboard"}
]
for item in items:
if item["userId"] == userId:
return Maybe(item)
return Maybe(None)
def parseInt(input: str) -> Maybe:
try:
return Maybe(int(input))
except ValueError:
return Maybe(None)
if __name__ == '__main__':
kbd = [item["name"]
for code in parseInt("2012")
for yuzu in findUser(code)
for item in findItem(yuzu["id"])]
print(kbd) # => ['keyboard']
missing = [item["name"]
for code in parseInt("3308")
for yui in findUser(code)
for item in findItem(yui["id"])]
print(missing) # => []
what = [item["name"]
for code in parseInt("wxyz")
for who in findUser(code)
for item in findItem(who["id"])]
print(what)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment