McNuggets problem: Difference between revisions

Content added Content deleted
(→‎Python List monad: (enumFromTo -> enumFromThenTo))
Line 835: Line 835:


Note that the innermost function wraps its results in a (potentially empty) list. The resulting list of lists, some empty, is then flattened by the concatenation component of '''bind'''.
Note that the innermost function wraps its results in a (potentially empty) list. The resulting list of lists, some empty, is then flattened by the concatenation component of '''bind'''.
<lang python>'''mcNuggets list monad'''
<lang python>from itertools import (chain, count, dropwhile, islice)

from itertools import (chain, count, dropwhile, islice)




def main():
def main():
'''List monad equivalent of the list (or set) comprehension.'''
'''List monad equivalent of the list (or set) comprehension.'''

def size(n):
def size(n):
return enumFromTo(0)(100 // n)
return enumFromThenTo(0)(n)(100)


mcNuggets = set(
mcNuggets = set(
bind(size(6))(lambda x:
bind(size(6))(
bind(size(9))(lambda y:
lambda x:
bind(size(20))(lambda z: (
bind(size(9))(
lambda v=sum([6 * x, 9 * y, 20 * z]): (
lambda y:
[v] if 101 > v else []
bind(size(20))(
)
lambda z: (
lambda v=sum([x, y, z]): (
)())))
[v] if 101 > v else []
)
)())))
)
)


Line 885: Line 891:
list(range(m, 1 + n, next - m))
list(range(m, 1 + n, next - m))
)
)


# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))