functional.hpp 1.42 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
#ifndef MIGRAPH_GUARD_RTGLIB_FUNCTIONAL_HPP
#define MIGRAPH_GUARD_RTGLIB_FUNCTIONAL_HPP

#include <utility>

namespace migraph {

Paul's avatar
Paul committed
8
9
10
11
12
13
14
15
struct swallow
{
    template <class... Ts>
    constexpr swallow(Ts&&...)
    {
    }
};

Paul's avatar
Paul committed
16
17
namespace detail {

Paul's avatar
Paul committed
18
template <class R, class F>
Paul's avatar
Paul committed
19
20
21
22
struct fix_f
{
    F f;

Paul's avatar
Paul committed
23
    template <class... Ts>
Paul's avatar
Paul committed
24
25
26
27
28
29
    R operator()(Ts&&... xs) const
    {
        return f(*this, std::forward<Ts>(xs)...);
    }
};

Paul's avatar
Paul committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
template <std::size_t...>
struct seq
{
    using type = seq;
};

template <class, class>
struct merge_seq;

template <std::size_t... Xs, std::size_t... Ys>
struct merge_seq<seq<Xs...>, seq<Ys...>> : seq<Xs..., (sizeof...(Xs) + Ys)...>
{
};

template <std::size_t N>
struct gens : merge_seq<typename gens<N / 2>::type, typename gens<N - N / 2>::type>
{
};

template <>
struct gens<0> : seq<>
{
};
template <>
struct gens<1> : seq<0>
{
};

template <class F, std::size_t... Ns>
constexpr void repeat_c_impl(F f, seq<Ns...>)
{
    swallow{(f(std::integral_constant<std::size_t, Ns>{}), 0)...};
}

Paul's avatar
Paul committed
64
65
} // namespace detail

Paul's avatar
Paul committed
66
template <std::size_t N, class F>
Paul's avatar
Paul committed
67
68
69
70
71
constexpr void repeat_c(F f)
{
    detail::repeat_c_impl(f, detail::gens<N>{});
}

Paul's avatar
Paul committed
72
/// Implements a fix-point combinator
Paul's avatar
Paul committed
73
template <class R, class F>
Paul's avatar
Paul committed
74
75
76
77
78
detail::fix_f<R, F> fix(F f)
{
    return {f};
}

Paul's avatar
Paul committed
79
template <class F>
Paul's avatar
Paul committed
80
81
82
83
84
auto fix(F f)
{
    return fix<void>(f);
}

Paul's avatar
Paul committed
85
template <class... Ts>
Paul's avatar
Paul committed
86
auto pack(Ts... xs)
87
{
Paul's avatar
Paul committed
88
    return [=](auto f) { return f(xs...); };
89
90
}

Paul's avatar
Paul committed
91
92
93
} // namespace migraph

#endif