问题:
- 这是单子吗?
- 这是否表明对错误单子的合理理解?
- 我错过了什么?
- 我还能用这段代码做什么来更多地弯曲单子?
- 我对成功/失败与“返回”/“结果”/“提升”的关系感到困惑(我认为这些都是相同的概念)。
- 我们怎样才能让问题变得更复杂,这样 monad 才能帮助我们解决我们的痛点?monad 在这里有帮助,因为我们抽象了
if result != None
管道,我还想抽象哪些其他类型的管道,以及 monad(或“monad 组合器”)如何帮助这种痛苦?
我有点不知所措。
# helpers for returning error codes
def success(x): return (True, x)
def fail(x): return (False, x)
# bind knows how to unwrap the return value and pass it to
# the next function
def bind(mv, mf):
succeeded = mv[0]
value = mv[1]
if (succeeded): return mf(value)
else: return mv
def lift(val): return success(val)
def userid_from_name(person_name):
if person_name == "Irek": return success(1)
elif person_name == "John": return success(2)
elif person_name == "Alex": return success(3)
elif person_name == "Nick": return success(1)
else: return fail("No account associated with name '%s'" % person_name)
def balance_from_userid(userid):
if userid == 1: return success(1000000)
elif userid == 2: return success(75000)
else: return fail("No balance associated with account #%s" % userid)
def balance_qualifies_for_loan(balance):
if balance > 200000: return success(balance)
else: return fail("Insufficient funds for loan, current balance is %s" % balance)
def name_qualifies_for_loan(person_name):
"note pattern of lift-bind-bind-bind, we can abstract further with macros"
mName = lift(person_name)
mUserid = bind(mName, userid_from_name)
mBalance = bind(mUserid, balance_from_userid)
mLoan = bind(mBalance, balance_qualifies_for_loan)
return mLoan
for person_name in ["Irek", "John", "Alex", "Nick", "Fake"]:
qualified = name_qualifies_for_loan(person_name)
print "%s: %s" % (person_name, qualified)
输出:
Irek: (True, 1000000)
John: (False, 'Insufficient funds for loan, current balance is 75000')
Alex: (False, 'No balance associated with account #3')
Nick: (True, 1000000)
Fake: (False, "No account associated with name 'Fake'")