简体   繁体   中英

Converting to Functional style

I wrote the following method in python that finds the intersection of 2 segments on a plane (assuming the segments are parallel to either the x or y axis)

segment_endpoints = []

def intersection(s1, s2):

  segment_endpoints = [] left = max(min(s1[0], s1[2]), min(s2[0], s2[2])) right = min(max(s1[0], s1[2]), max(s2[0], s2[2])) top = max(min(s1[1], s1[3]), min(s2[1], s2[3])) bottom = min(max(s1[1], s1[3]), max(s2[1], s2[3])) if top > bottom or left > right: segment_endpoints = [] return 'NO INTERSECTION' elif top == bottom and left == right: segment_endpoints.append(left) segment_endpoints.append(top) return 'POINT INTERSECTION' else: segment_endpoints.append(left) segment_endpoints.append(bottom) segment_endpoints.append(right) segment_endpoints.append(top) return 'SEGMENT INTERSECTION' 

Can this be considered in good functional form? If not what would be the proper functional way of rewriting it?

I think the code can be refactored as follows, but not necessarily a functional style.

def intersection(s1, s2):

    left = max(min(s1[0], s1[2]), min(s2[0], s2[2]))
    right = min(max(s1[0], s1[2]), max(s2[0], s2[2]))
    top = max(min(s1[1], s1[3]), min(s2[1], s2[3]))
    bottom = min(max(s1[1], s1[3]), max(s2[1], s2[3]))

    if top > bottom or left > right:
        return ('NO INTERSECTION',dict())
    if (top,left) == (bottom,right):
        return ('POINT INTERSECTION',dict(left=left,top=top))
    return ('SEGMENT INTERSECTION',dict(left=left,bottom=bottom,right=right,top=top))

You are abusing strings. I would consider returning integers instead of strings and defining something like:

class IntersectionType:
  NO_INTERSECTION = 1
  POINT_INTERSECTION = 2
  SEGMENT_INTERSECTION = 3

Python 3.4 also contains enums: How can I represent an 'Enum' in Python? ... so if you're using Python 3.4 then this would be a use case for enums.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM