Department numbers: Difference between revisions

→‎{{header|Python}}: Updated bind, pylinted for Python 3, added subheaders.
(Added Algol W)
(→‎{{header|Python}}: Updated bind, pylinted for Python 3, added subheaders.)
Line 1,935:
 
=={{header|Python}}==
===Procedural===
<lang python>from itertools import permutations
Line 1,966 ⟶ 1,967:
14: 6 5 1 </pre>
 
===Composition of pure functions===
Or, expressingExpressing the options directly and declaratively in terms of a '''reduce'bind'' and '''add'''operator, without importing ''permutations'':
{{Works with|Python|3}}
<lang python>'''Department numbers'''
 
<lang python>from functoolsitertools import (reducechain)
from operator import (addne)
 
 
# options :: Int -> Int -> Int -> [(Int, Int, Int)]
def options(lo, hi, total):
'''Eligible integer triples.'''
ds = rangeenumFromTo(lo, 1 + )(hi)
return bind(filter(lambda x: 0 == x % 2, ds))(
lambda x:return bind(filter(lambda d: d != xeven, ds))(
lambda x: bind(filter(curry(ne)(x), ds))(
lambda y: bind([total - (x + y)])(
lambda z: [(x, y, z)] if (
z != y and zlo ><= lo and z <= hi
) else []
)
Line 1,987 ⟶ 1,992:
 
# TEST ----------------------------------------------------
 
 
# main :: IO ()
def main():
'''Test'''
 
xs = options(1, 7, 12)
print (('Police', 'Sanitation', 'Fire'))
for tpl in xs:
print (tpl)
print ('\nNo. of options: ' + str(len(xs)))
 
 
# GENERIC ABSTRACTIONABSTRACTIONS -------------------------------------
 
# bind (>>=) :: [a] -> (a -> [b]) -> [b]
def bind(xs):
'''List monad injection operator.
return lambda f: reduce(add, map(f, xs), [])
Two computations sequentially composed,
with any value produced by the first
passed as an argument to the second.'''
return lambda f: list(
chain.from_iterable(
map(f, xs)
)
)
 
 
# curry :: ((a, b) -> c) -> a -> b -> c
main()</lang>
def curry(f):
'''A curried function derived
from an uncurried function.'''
return bind(filter(lambda xa: 0lambda ==b: x % 2f(a, dsb))(
 
 
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda fn: reducelist(add, maprange(fm, xs1 + n), [])
 
 
# even :: Int -> Bool
def even(x):
'''True if x is an integer
multiple of two.'''
return 0 == x % 2
 
 
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>('Police', 'Sanitation', 'Fire')
9,659

edits