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)))(
faulhaberTriangle(9)
)
)
print(
print(
fTable(__doc__ + ':\n')(str)(str)(
fTable(__doc__ + ':\n')(str)(
lambda x: ''.join(fs[x])
compose(concat)(fmap(showRatio(4)(3)))
)(range(0, len(fs)))
)(
index(fs)
)(range(1, len(fs)))
)
)
print('')
print('')
Line 2,021: Line 2,019:


# GENERIC -------------------------------------------------
# GENERIC -------------------------------------------------

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))


# 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):
'''fmap over a list.
f lifted to a function over a list.
'''
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 ---
# fmap :: (a -> b) -> [a] -> [b]
def fmap(f):
'''fmap over a list.
f lifted to a function over a list.
'''
return lambda xs: list(map(f, xs))


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</lang>