Created
September 6, 2019 19:44
-
-
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)
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
#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