Skip to content

Instantly share code, notes, and snippets.

@lquenti
Created September 6, 2019 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lquenti/af8ef786d3ac19de559af64d0eece9d4 to your computer and use it in GitHub Desktop.
Save lquenti/af8ef786d3ac19de559af64d0eece9d4 to your computer and use it in GitHub Desktop.
Example for higher kinded types in C++ with std::list and std::optional (Maybe)
#include<list>
#include<optional>
template<template <typename> class F>
struct Functor {
template<typename A, typename B>
static F<B> fmap(B *(f)(A), F<A> val);
// ($>)
template<typename A, typename B>
static F<A> replaceFunctor(A a, F<B> list);
};
template<>
struct Functor<std::list> {
template<typename A, typename B>
static std::list<B> fmap(B *(f)(A), std::list<A> list) {
for (auto x : list) x = f(x);
}
template<typename A, typename B>
static std::list<A> replaceFunctor(A a, std::list<B> list) {
return new std::list<A>(a);
}
};
template<>
struct Functor<std::optional> {
template<typename A, typename B>
static std::optional<B> fmap(B *(f)(A), std::optional<A> maybe) {
return maybe.has_value() ? maybe.emplace(f(maybe.get())) : maybe;
}
template<typename A, typename B>
static std::optional<A> replaceFunctor(A a, std::optional<B> maybe) {
return new std::optional(a);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment