修改不可变的子结构

Yak*_*ont 6 c++ monads immutability algebraic-data-types c++17

假设我有一个不可变的包装器:

template<class T>
struct immut {
  T const& get() const {return *state;}
  immut modify( std::function<T(T)> f ) const { return immut{f(*state)}; }
  immut(T in):state(std::make_shared<T>(std::move(in))){}
private:
  std::shared_ptr<T const> state;
};
Run Code Online (Sandbox Code Playgroud)

如果我有immut<Bob> b,我可以把一个Bob(Bob)操作变成可以取代我的东西b.

template<class T>
std::function<immut<T>(immut<T>)> on_immut( std::function<void(T&)> f ){
  return [=](auto&&in){ return in.modify( [&](auto t){ f(t); return t; } ); };
}
Run Code Online (Sandbox Code Playgroud)

所以,如果Bobint x,y;,我可以将天真可变代码[](auto& b){ b.x++; }转换为immut<Bob>更新程序.


现在,如果Bob反过来又有immut<Alice>成员,而immut<Charlie>成员又有成员.

假设我有一个Charlie更新程序,void(Charlie&).我知道Charlie我想要更新的地方是.在可变的土地上,它看起来像:

void update( Bob& b ){
  modify_charlie(b.a.c[77]);
}
Run Code Online (Sandbox Code Playgroud)

我可能会把它分成:

template<class S, class M>
using get=std::function<M&(S&)>;
template<class X>
using update=std::function<void(X&)>;
template<class X>
using produce=std::function<X&()>;

void update( produce<Bob> b, get<Bob, Alice> a, get<Alice, Charlie> c, update<Charlie> u ){
  u(c(a(b())));
}
Run Code Online (Sandbox Code Playgroud)

甚至去代数并有(伪代码):

get<A,C> operator|(get<A,B>,get<B,C>);
update<A> operator|(get<A,B>,update<B>);
produce<B> operator|(produce<A>,get<A,B>);
void operator|(produce<A>, update<A>);
Run Code Online (Sandbox Code Playgroud)

让我们根据需要将运营联系在一起.

void update( produce<Bob> b, get<Bob, Alice> a, get<Alice, Charlie> c, update<Charlie> u ){std::
  u(c(a(b())));
}
Run Code Online (Sandbox Code Playgroud)

b|a|c|u;
Run Code Online (Sandbox Code Playgroud)

步骤可以在任何地方拼接在一起.


与immuts相同的是什么,它有一个名字吗?理想情况下,我希望这些步骤在可变的情况下是孤立的但可组合的,天真的"叶子代码"在可变状态结构上.

lll*_*lll 6

与immuts相同的是什么,它有一个名字吗?

IDK是否存在子状态操作的通用名称.但是在Haskell中,有一个Lens提供你想要的东西.

在C++中,您可以将a lens视为一对getter和setter函数,两者都只关注其直接子部分.然后有一个作曲家将两个镜头组合在一起,聚焦在一个结构的更深的子部分上.

// lens for `A` field in `D`
template<class D, class A>
using get = std::function<A const &(D const &)>;

template<class D, class A>
using set = std::function<D(D const &, A)>;

template<class D, class A>
using lens = std::pair<get<D, A>, set<D, A>>;

// compose (D, A) lens with an inner (A, B) lens,
// return a (D, B) lens
template<class D, class A, class B>
lens<D, B>
lens_composer(lens<D, A> da, lens<A, B> ab) {
    auto abgetter = ab.first;
    auto absetter = ab.second;
    auto dagetter = da.first;
    auto dasetter = da.second;

    get<D, B> getter = [abgetter, dagetter]
        (D const &d) -> B const&
    {
        return abgetter(dagetter(d));
    };

    set<D, B> setter = [dagetter, absetter, dasetter]
        (D const &d, B newb) -> D
    {
        A const &a = dagetter(d);
        A newa = absetter(a, newb);
        return dasetter(d, newa);
    };

    return {getter, setter};
};
Run Code Online (Sandbox Code Playgroud)

你可以写一个像这样的基本镜头:

struct Bob {
    immut<Alice> alice;
    immut<Anna>  anna;
};
auto bob_alice_lens
= lens<Bob, Alice> {
    [] (Bob const& b) -> Alice const & {
        return b.alice.get();
    },
    [] (Bob const& b, Alice newAlice) -> Bob {
        return { immut{newAlice}, b.anna };
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,此过程可以通过宏自动执行.

然后,如果Bob包含immut<Alice>,Alice包含immut<Charlie>,你可以写2个镜头(BobAliceAliceCharlie)时,BobCharlie镜头可以通过组成:

auto bob_charlie_lens = 
lens_composer(bob_alice_lens, alice_charlie_lens);
Run Code Online (Sandbox Code Playgroud)

现场演示

注意:

下面是一个更完整的示例,线性内存增长深度,没有类型擦除开销(std::function),并且具有完整的编译时类型检查.它还使用宏来生成基本镜头.

#include <type_traits>
#include <utility>

template<class T>
using GetFromType = typename T::FromType;

template<class T>
using GetToType = typename T::ToType;

// `get` and `set` are fundamental operations for Lens,
// this Mixin will add utilities based on `get` and `set`
template<class Derived>
struct LensMixin {
    Derived &self() { return static_cast<Derived&>(*this); }

    // f has type: A& -> void
    template<class D, class Mutation>
    auto modify(D const &d, Mutation f)
    {
        auto a = self().get(d);
        f(a);
        return self().set(d, a);
    }
};

template<
    class Getter, class Setter,
    class D, class A
    >
struct SimpleLens : LensMixin<SimpleLens<Getter, Setter, D, A>> {
    static_assert(std::is_same<
            std::invoke_result_t<Getter, const D&>, const A&>{},
            "Getter should return const A& for (const D&)");

    static_assert(std::is_same<
            std::invoke_result_t<Setter, const D&, A>, D>{},
            "Setter should return D for (const D&, A)");
    using FromType = D;
    using ToType = A;

    SimpleLens(Getter getter, Setter setter)
        : getter(getter)
        , setter(setter)
    {}

    A const &get(D const &d) { return getter(d); }
    D set(D const &d, A newa) { return setter(d, newa); }
private:
    Getter getter;
    Setter setter;
};

template<
    class LensDA, class LensAB
    >
struct ComposedLens : LensMixin<ComposedLens<LensDA, LensAB>> {
    static_assert(std::is_same<
            GetToType<LensDA>, GetFromType<LensAB>
        >{}, "Cannot compose two Lens with wrong intermediate type");

    using FromType = GetFromType<LensDA>;
    using ToType = GetToType<LensAB>;

private:
    using intermediateType = GetToType<LensDA>;
    using D = FromType;
    using B = ToType;
    LensDA da;
    LensAB ab;
public:

    ComposedLens(LensDA da, LensAB ab) : da(da), ab(ab) {}

    B const &get(D const &d) { return ab.get(da.get(d)); }
    D set(D const &d, B newb) {
        const auto &a = da.get(d);
        auto newa = ab.set(a, newb);
        return da.set(d, newa);
    }
};

namespace detail {
    template<class LensDA, class LensAB>
    auto MakeComposedLens(LensDA da, LensAB ab) {
        return ComposedLens<LensDA, LensAB> { da, ab };
    }

    template<class D, class A, class Getter, class Setter>
    auto MakeSimpleLens(Getter getter, Setter setter)
    {
        return SimpleLens<Getter, Setter, D, A> {
            getter, setter
        };
    }
}

template<class LensDA, class LensAB>
auto lens_composer(LensDA da, LensAB ab) {
    return detail::MakeComposedLens (da, ab);
}


#include <memory>

template<class T>
struct immut {
  T const& get() const {return *state;}
  immut(T in):state(std::make_shared<T>(std::move(in))){}
private:
  std::shared_ptr<T const> state;
};

#define MAKE_SIMPLE_LENS(D, A, Aname)   \
    detail::MakeSimpleLens<D, A>(       \
        +[] (D const &d) -> A const & { \
            return d . Aname . get();   \
        },                              \
        +[] (D const &d, A newa) -> D { \
            D newd = d;                 \
            newd . Aname = newa;        \
            return newd;                \
        })




struct Charlie {
    int id = 0;
};

struct Alice{
    immut<Charlie> charlie;
};
struct Anna {};
struct Bob {
    immut<Alice> alice;
    immut<Anna>  anna;
};

auto alice_charlie_lens = MAKE_SIMPLE_LENS(Alice, Charlie, charlie);
auto bob_alice_lens     = MAKE_SIMPLE_LENS(Bob, Alice, alice);
auto bob_charlie_lens   = lens_composer(bob_alice_lens, alice_charlie_lens);

static_assert(std::is_same<GetFromType<decltype(bob_charlie_lens)>, Bob>{});
static_assert(std::is_same<GetToType<decltype(bob_charlie_lens)>, Charlie>{});

#include <iostream>

int main() {
    immut<Charlie> charlie{Charlie{77}};
    immut<Alice> alice{Alice{charlie}};
    immut<Anna>  anna{Anna{}};

    Bob bob{alice, anna};
    std::cout << "bob     -> anna: " << static_cast<void const*>(&bob.anna.get()) << "\n";
    std::cout << "bob     -> charlie: " << bob_charlie_lens.get(bob).id << "\n";

    // Bob newbob = bob_charlie_lens.set(bob, Charlie{148});
    Bob newbob = bob_charlie_lens.modify(bob, [] (auto &charlie) {
            charlie.id += (148 - 77);
            });
    std::cout << "new bob -> anna: " << static_cast<void const*>(&bob.anna.get()) << "\n";
    std::cout << "old bob -> charlie: " << bob_charlie_lens.get(bob).id << "\n";
    std::cout << "new bob -> charlie: " << bob_charlie_lens.get(newbob).id << "\n";
}
Run Code Online (Sandbox Code Playgroud)