受哈克尔启发的python一元do符号
guac的Python项目详细描述
一元do符号
guac在python中提供了一元do符号,灵感来自haskell。monad提供“可编程分号”,通过它可以更改程序的行为。一个常见的、有用的monad是list monad,它表示不确定的计算。list monad使编写回溯搜索变得非常容易。
要求
guac需要python 3的一个实现,它支持生成函数上的copy.deepcopy。最常见的发行版cpython缺少这个特性,但是pypy实现了它!
示例
下面是一个例子,它计算了所有可能的方法,你可以给0.47美元的零钱,硬币,硬币和硬币:
fromguacimport*@monadic(ListMonad)defmake_change(amount_still_owed,possible_coins):change=[]# Keep adding coins while we owe them money and there are still coins.whileamount_still_owed>0andpossible_coins:# "Nondeterministically" choose whether to give anther coin of this value.# Aka, try both branches, and return both results.give_min_coin=yield[True,False]ifgive_min_coin:# Give coinmin_coin=possible_coins[0]change.append(min_coin)amount_still_owed-=min_coinelse:# Never give this coin value again (in this branch!)delpossible_coins[0]# Did we charge them the right amount?yieldguard(amount_still_owed==0)# Lift the result back into the monad.yieldlift(change)print(make_change(27,[1,5,10,25]))
运行这个程序将打印一个列表列表,每个列表包含一组不同的数字,总计27个。你可以想象很多很酷的方法来使用它,从统一到解析!
要了解更多信息,请查看自述文件。