Kleisli Categories
Prev: Categories Great and Small Next: Products and Coproducts
Prev: Categories Great and Small Next: Products and Coproducts
Exercises
A function that is not defined for all possible values of its argument is called a partial function. It’s not really a function in the mathematical sense, so it doesn’t fit the standard categorical mold. It can, however, be represented by a function that returns an embellished type optional:
template<typename A>
class optional {
bool _isValid;
A _value;
public:
optional() : _isValid(false) {}
optional(A v) : _isValid(true), _value(v) {}
bool isValid() const { return _isValid; }
A value() const { return _value; }
};For example, here’s the implementation of the embellished function safe_root:
optional<double> safe_root(double x) {
if (x >= 0) return optional<double>{sqrt(x)};
else return optional<double>{};
}Here’s the challenge:
- Construct the Kleisli category for partial functions (define composition and identity).
- Implement the embellished function
safe_reciprocalthat returns a valid reciprocal of its argument, if it’s different from zero. - Compose the functions
safe_rootandsafe_reciprocalto implementsafe_root_reciprocalthat calculatessqrt(1/x)whenever possible.