Hilbert curve: Difference between revisions

Content added Content deleted
m (→‎Python Functional: Updated primitives. Tidied.)
Line 2,213: Line 2,213:
<lang Python>'''Hilbert curve'''
<lang Python>'''Hilbert curve'''


from itertools import (chain, islice, starmap)
from itertools import (chain, islice)
from inspect import signature




Line 2,278: Line 2,277:
def go(xy, tree):
def go(xy, tree):
r = d // 2
r = d // 2

centres = map(
lambda v: (
def deltas(v):
return (
xy[0] + (r * v[0]),
xy[0] + (r * v[0]),
xy[1] + (r * v[1])
xy[1] + (r * v[1])
),
)
vectors[tree['root']]
centres = map(deltas, vectors[tree['root']])
)
return chain.from_iterable(
return chain.from_iterable(
starmap(points(r), zip(centres, tree['nest']))
map(points(r), centres, tree['nest'])
) if tree['nest'] else centres
) if tree['nest'] else centres
return lambda xy, tree: go(xy, tree)
return go


d = w // 2
d = w // 2
Line 2,298: Line 2,297:
'''Width of square canvas -> Point list -> SVG string'''
'''Width of square canvas -> Point list -> SVG string'''


def go(w, xys):
def go(xys):
xs = ' '.join(map(
def points(xy):
lambda xy: str(xy[0]) + ' ' + str(xy[1]),
return str(xy[0]) + ' ' + str(xy[1])
xys
xs = ' '.join(map(points, xys))
))
return '\n'.join(
return '\n'.join(
['<svg xmlns="http://www.w3.org/2000/svg"',
['<svg xmlns="http://www.w3.org/2000/svg"',
Line 2,311: Line 2,309:
]
]
)
)
return lambda xys: go(w, xys)
return go




# TEST ----------------------------------------------------
# ------------------------- TEST --------------------------
def main():
def main():
'''Testing generation of the SVG for a Hilbert curve'''
'''Testing generation of the SVG for a Hilbert curve'''
Line 2,320: Line 2,318:
hilbertCurve(6)
hilbertCurve(6)
)
)
print()




# GENERIC FUNCTIONS ---------------------------------------
# ------------------- GENERIC FUNCTIONS -------------------


# Node :: a -> [Tree a] -> Tree a
# Node :: a -> [Tree a] -> Tree a
Line 2,335: Line 2,334:
def flip(f):
def flip(f):
'''The (curried or uncurried) function f with its
'''The (curried or uncurried) function f with its
arguments reversed.'''
arguments reversed.
'''
if 1 < len(signature(f).parameters):
return lambda a, b: f(b, a)
return lambda a: lambda b: f(b)(a)
else:
return lambda a: lambda b: f(b)(a)




Line 2,352: Line 2,349:
yield v
yield v
v = f(v)
v = f(v)
return lambda x: go(x)
return go