Last active
March 15, 2020 19:12
-
-
Save mpkocher/04000b6d33477ef9e716d63bab3ea69b to your computer and use it in GitHub Desktop.
Example of a functional-ish centric design encoding logic in a rules based model #LevelUp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Example of a functional-ish centric design and encoding logic in rules. | |
This uses determination of a leap year as an simple example. | |
This approach could be used in more involved cases to encode business logic. | |
""" | |
import operator as op | |
LEAP_YEARS = [ | |
1904, | |
1908, | |
1912, | |
1916, | |
1920, | |
1924, | |
1928, | |
1932, | |
1936, | |
1940, | |
1944, | |
1948, | |
1952, | |
1956, | |
1960, | |
1964, | |
1968, | |
1972, | |
1976, | |
1980, | |
1984, | |
1988, | |
1992, | |
1996, | |
2000, | |
2004, | |
2008, | |
2012, | |
2016, | |
2020, | |
] | |
def is_leap(year: int) -> bool: | |
"""Vanilla Solution""" | |
state = False | |
if (year % 4) == 0: | |
if (year % 100) == 0: | |
if (year % 400) == 0: | |
state = True | |
else: | |
state = True | |
return state | |
def to_rule(n: int, comparer=op.eq): | |
def f(year_: int) -> bool: | |
return comparer((year_ % n), 0) | |
return f | |
def apply(funcs, year) -> bool: | |
return all(f(year) for f in funcs) | |
def to_apply(funcs): | |
def f(year): | |
return apply(funcs, year) | |
return f | |
def is_leap2(year: int) -> bool: | |
"""Rule based approach""" | |
case0 = to_apply(map(to_rule, (4, 100, 400))) | |
case1 = to_apply((to_rule(4), to_rule(100, op.ne))) | |
return any(f(year) for f in (case0, case1)) | |
def runner(func=is_leap): | |
print(f"Running func {func.__name__}") | |
leap_years = set(LEAP_YEARS) | |
results = {year for year in range(1900, 2021) if func(year)} | |
years = leap_years ^ results | |
msg = f"Incorrect results found {years}" if years else "Found correct leap years." | |
print(msg) | |
return years | |
def demo(): | |
funcs = (is_leap, is_leap2) | |
_ = list(map(runner, funcs)) | |
return 0 | |
if __name__ == "__main__": | |
demo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment