1// Copyright Louis Dionne 2013-2022
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
4
5#include <boost/hana/ap.hpp>
6#include <boost/hana/assert.hpp>
7#include <boost/hana/bool.hpp>
8#include <boost/hana/config.hpp>
9#include <boost/hana/equal.hpp>
10#include <boost/hana/if.hpp>
11#include <boost/hana/lift.hpp>
12#include <boost/hana/optional.hpp>
13namespace hana = boost::hana;
14
15
16template <char op>
17constexpr auto function = hana::nothing;
18
19template <>
20BOOST_HANA_CONSTEXPR_LAMBDA auto function<'+'> = hana::just([](auto x, auto y) {
21 return x + y;
22});
23
24template <>
25BOOST_HANA_CONSTEXPR_LAMBDA auto function<'-'> = hana::just([](auto x, auto y) {
26 return x - y;
27});
28
29// and so on...
30
31template <char n>
32constexpr auto digit = hana::if_(hana::bool_c<(n >= '0' && n <= '9')>,
33 hana::just(static_cast<int>(n - 48)),
34 hana::nothing
35);
36
37template <char x, char op, char y>
38BOOST_HANA_CONSTEXPR_LAMBDA auto evaluate = hana::ap(function<op>, digit<x>, digit<y>);
39
40int main() {
41 BOOST_HANA_CONSTEXPR_CHECK(evaluate<'1', '+', '2'> == hana::just(1 + 2));
42 BOOST_HANA_CONSTEXPR_CHECK(evaluate<'4', '-', '2'> == hana::just(4 - 2));
43
44 BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '+', '2'> == hana::nothing);
45 BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '?', '2'> == hana::nothing);
46 BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '+', '?'> == hana::nothing);
47 BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '?', '?'> == hana::nothing);
48
49 static_assert(hana::lift<hana::optional_tag>(123) == hana::just(123), "");
50}
51

source code of boost/libs/hana/example/optional/applicative.complex.cpp