Find the intersection of two lines: Difference between revisions
m
→{{header|Python}}: Updated one primitive
m (→{{header|Python}}: Updated one primitive) |
|||
Line 1,356:
=={{header|Python}}==
Find the intersection
<lang python>def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
""" returns a (x, y) tuple or None if there is no intersection """
Line 1,386:
{{Works with|Python|3.7}}
<lang python>'''The intersection of two lines.'''
from
# intersection :: Line -> Line -> Either String Point
def intersection(ab):
Line 1,397:
def delta(f):
return lambda x: f(fst(x)) - f(snd(x))
def prodDiff(abcd):
[a, b, c, d] = abcd
return (a * d) - (b * c)
def go(pq):
[abDX, pqDX, abDY, pqDY] =
[delta(fst), delta(snd)]
)([ab, pq])
determinant = prodDiff([abDX, abDY, pqDX, pqDY])
def point():
[abD, pqD] = map(
lambda xy: prodDiff(
), [ab, pq]
)
return
[lambda abpq: prodDiff(
[abD, fst(abpq), pqD, snd(abpq)]) / determinant]
Line 1,423:
'( Parallel lines - no intersection )'
)
return lambda pq: bindLR(go(pq))(
lambda xs: Right((fst(xs), snd(xs)))
)
#
# main :: IO()
def main():
'''Test'''
# Left(message - no intersection) or Right(point)
# lrPoint :: Either String Point
Line 1,444:
lrPoint['Left'] or lrPoint['Right']
)
#
# Left :: a -> Either a b
def Left(x):
Line 1,453:
with an associated string.'''
return {'type': 'Either', 'Right': None, 'Left': x}
# Right :: b -> Either a b
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
#
def
'''The application of each of a list of functions,
to each of a list of values.
return lambda xs: reduce(▼
def go(fx):
return f(x)
▲ )
go(x) for x
in product(fs, xs)
]
# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
def bindLR(m):
Line 1,481 ⟶ 1,484:
mf(m.get('Right')) if None is m.get('Left') else m
)
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# MAIN ---
if __name__ == '__main__':
|