Skip to content

Commit f15abcd

Browse files
rosdsAlfonso Ros
andauthored
Update 1.3's C++ concept implementation of Monoid (#259)
Co-authored-by: Alfonso Ros <alfonso.ros@esrlabs.com>
1 parent fab316e commit f15abcd

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

src/content/1.3/categories-great-and-small.tex

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -177,41 +177,42 @@ \section{Monoid as Set}
177177
so this might be a little confusing to the beginner.)
178178

179179
The closest one can get to declaring a monoid in C++ would be to use the
180-
(proposed) syntax for concepts.
180+
C++20 standard's concept feature.
181181

182182
\begin{snip}{cpp}
183183
template<class T>
184-
T mempty = delete;
185-
184+
struct mempty;
185+
186186
template<class T>
187-
T mappend(T, T) = delete;
188-
189-
template<class M>
190-
concept bool Monoid = requires (M m) {
191-
{ mempty<M> } -> M;
192-
{ mappend(m, m); } -> M;
193-
};
187+
T mappend(T, T) = delete;
188+
189+
template<class M>
190+
concept Monoid = requires (M m) {
191+
{ mempty<M>::value() } -> std::same_as<M>;
192+
{ mappend(m, m) } -> std::same_as<M>;
193+
};
194194
\end{snip}
195-
The first definition uses a value template (also proposed). A
196-
polymorphic value is a family of values --- a different value for every
197-
type.
195+
The first definition is a structure meant to hold the neutral element for each
196+
specialization.
198197

199198
The keyword \code{delete} means that there is no default value
200199
defined: It will have to be specified on a case-by-case basis.
201200
Similarly, there is no default for \code{mappend}.
202201

203-
The concept \code{Monoid} is a predicate (hence the \code{bool}
204-
type) that tests whether there exist appropriate definitions of
202+
The concept \code{Monoid} tests whether there exist appropriate definitions of
205203
\code{mempty} and \code{mappend} for a given type \code{M}.
206204

207205
An instantiation of the Monoid concept can be accomplished by providing
208206
appropriate specializations and overloads:
209207

210208
\begin{snip}{cpp}
211209
template<>
212-
std::string mempty<std::string> = {""};
210+
struct mempty<std::string> {
211+
static std::string value() { return ""; }
212+
};
213213

214-
std::string mappend(std::string s1, std::string s2) {
214+
template<>
215+
std::string mappend(std::string s1, std::string s2) {
215216
return s1 + s2;
216217
}
217218
\end{snip}

0 commit comments

Comments
 (0)