Faulhaber's triangle: Difference between revisions
Content added Content deleted
m (→{{header|Python}}: (Tidied test section)) |
|||
Line 1,948: | Line 1,948: | ||
<lang python>'''Faulhaber's triangle''' |
<lang python>'''Faulhaber's triangle''' |
||
from itertools import (accumulate, count, islice, starmap) |
from itertools import (accumulate, chain, count, islice, starmap) |
||
from fractions import (Fraction) |
from fractions import (Fraction) |
||
Line 1,984: | Line 1,984: | ||
'''Tests''' |
'''Tests''' |
||
fs = ( |
fs = faulhaberTriangle(9) |
||
fmap(fmap(showRatio(4)(2)))( |
|||
⚫ | |||
⚫ | |||
⚫ | |||
print( |
print( |
||
fTable(__doc__ + ':\n' |
fTable(__doc__ + ':\n')(str)( |
||
compose(concat)(fmap(showRatio(4)(3))) |
|||
)( |
)( |
||
⚫ | |||
)(range(1, len(fs))) |
|||
) |
) |
||
print('') |
print('') |
||
Line 2,021: | Line 2,019: | ||
# GENERIC ------------------------------------------------- |
# GENERIC ------------------------------------------------- |
||
⚫ | |||
⚫ | |||
'''Right to left function composition.''' |
|||
⚫ | |||
# concat :: [[a]] -> [a] |
|||
# concat :: [String] -> String |
|||
def concat(xs): |
|||
'''The concatenation of all the elements |
|||
in a list or iterable.''' |
|||
def f(ys): |
|||
zs = list(chain(*ys)) |
|||
return ''.join(zs) if isinstance(ys[0], str) else zs |
|||
return ( |
|||
f(xs) if isinstance(xs, list) else ( |
|||
chain.from_iterable(xs) |
|||
⚫ | |||
) if xs else [] |
|||
# fmap :: (a -> b) -> [a] -> [b] |
|||
def fmap(f): |
|||
⚫ | |||
⚫ | |||
⚫ | |||
return lambda xs: list(map(f, xs)) |
|||
# index (!!) :: [a] -> Int -> a |
|||
def index(xs): |
|||
'''Item at given (zero-based) index.''' |
|||
return lambda n: None if 0 > n else ( |
|||
xs[n] if ( |
|||
hasattr(xs, "__getitem__") |
|||
) else next(islice(xs, n, None)) |
|||
⚫ | |||
# showRatio :: Int -> Int -> Ratio -> String |
# showRatio :: Int -> Int -> Ratio -> String |
||
Line 2,037: | Line 2,075: | ||
# MAIN --- |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</lang> |
main()</lang> |