CUSIP: Difference between revisions
→Python :: Composition of pure functions: Pylinted for Python 3, tidied, added a {works with} tag
(→Python :: Composition of pure functions: Pylinted for Python 3, tidied, added a {works with} tag) |
|||
Line 1,748:
===Composition of pure functions===
{{Works with|Python|3.7}}
Composing a set of pure functions, including a number of general and reusable abstractions:
<lang python>
from itertools import (cycle, islice)
from functools import (reduce)
from operator import (add)
Line 1,758 ⟶ 1,761:
def isCusip(dct):
'''Test for the validity of a CUSIP string in the
context of a supplied dictionary of
'''
def go(s):
ns = [dct[c] for c in list(s) if c in dct]
Line 1,766 ⟶ 1,770:
sum(zipWith(
lambda f, x: add(*divmod(f(x), 10))
)(cycle([
take(8)(ns)
)) % 10
Line 1,796 ⟶ 1,800:
# main :: IO ()
def main():
'''
print(
)([
'037833100',
Line 1,814 ⟶ 1,815:
)
# GENERIC -------------------------------------------------▼
# FORMATTING ----------------------------------------------
# (b -> String) -> (a -> b) -> [a] -> String
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):▼
ys = [xShow(x) for x in xs]
xShow, fxShow, f, xs
)
▲# GENERIC -------------------------------------------------
# double :: Num -> Num
Line 1,852 ⟶ 1,873:
#
def
'''The identity function.'''
return x
▲# tabulated :: String -> (a -> b) -> [a] -> String
▲def tabulated(s):
▲ def go(f, xs):
▲ def width(x):
▲ w = width(max(xs, key=width))
▲ return s + '\n' + '\n'.join([
▲ str(x).rjust(w, ' ') + ' -> ' + str(f(x)) for x in xs
▲ ])
▲ return lambda f: lambda xs: go(f, xs)
Line 1,898 ⟶ 1,905:
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
'''A list constructed by zipping with a
custom function, rather than with the
default tuple constructor.
'''
return lambda xs: lambda ys: (
)
Line 1,908 ⟶ 1,918:
main()</lang>
{{Out}}
<pre>
037833100 -> True▼
'68389X106' -> False
'68389X105' -> True</pre>
=={{header|Racket}}==
|