Sierpinski triangle: Difference between revisions

Content added Content deleted
(Undo revision 294290 by Hout (talk))
(→‎{{header|Python}}: Fixed an inadvertent deletion, added docstrings and output.)
Line 3,216: Line 3,216:


and fold/reduce, wrapped as concatMap, can provide the list comprehensions too:
and fold/reduce, wrapped as concatMap, can provide the list comprehensions too:
<lang python>from functools import (reduce)
<lang python>'''Sierpinski triangle'''

from operator import (add)
from functools import reduce
from operator import add




# sierpinski :: Int -> String
# sierpinski :: Int -> String
def sierpinski(n):
def sierpinski(n):
'''Nth iteration of a Sierpinksi triangle.'''
def go(xs, i):
def go(xs, i):
s = ' ' * (2 ** i)
s = ' ' * (2 ** i)
Line 3,232: Line 3,235:
# concatMap :: (a -> [b]) -> [a] -> [b]
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
def concatMap(f):
'''A concatenated list or string over which a function f
has been mapped.
The list monad can be derived by using an (a -> [b])
function which wraps its output in a list (using an
empty list to represent computational failure).
'''
return lambda xs: (
return lambda xs: (
reduce(add, map(f, xs), [])
reduce(add, map(f, xs), [])
Line 3,238: Line 3,247:


print(sierpinski(4))</lang>
print(sierpinski(4))</lang>
{{Out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>