Trying to find a way to clean up some of my code.
So, I have something like this in my Python code:
company = None country = None person = Person.find(id=12345) if person is not None: # found company = Company.find(person.companyId) if company is not None: country = Country.find(company.countryId) return (person, company, country)
Having read a tutorial on Haskell's monads (in particular Maybe), I was wondering if it's possible to write it in another way.
In FP we often loosely say things like "arrays are monads" or "maybe values are monadic" etc. However, speaking more strictly, it is not the values (like [1, 2, 3] , Nothing , or Just(6) ) that are monads, but the context (the Array or Maybe "namespace" as you put it).
A monad is a design pattern that allows us to add a context to data values, and also allows us to easily compose existing functions so that they execute in a context aware manner.
Common monadsNondeterminism using List monad to represent carrying multiple values. State using State monad. Read-only environment using Reader monad. I/O using IO monad.
monads are used to address the more general problem of computations (involving state, input/output, backtracking, ...) returning values: they do not solve any input/output-problems directly but rather provide an elegant and flexible abstraction of many solutions to related problems.
company = country = None try: person = Person.find(id=12345) company = Company.find(person.companyId) country = Country.find(company.countryId) except AttributeError: pass # `person` or `company` might be None
EAFP
Exploit the short-circuit behavior and that a custom object is true by default and None
is false:
person = Person.find(id=12345) company = person and person.company country = company and company.country
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With