修改不可变的子结构

6
假设我有一个不可变的包装器:
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;
};

如果我有一个不可变的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; } ); };
}

所以如果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]);
}

我可能会将其拆分为以下几部分:

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())));
}

甚至可以使用代数语法,伪代码如下:
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>);

让我们将操作链接在一起,以满足需要。
void update( produce<Bob> b, get<Bob, Alice> a, get<Alice, Charlie> c, update<Charlie> u ){std::
  u(c(a(b())));
}

变成

b|a|c|u;

这里的步骤可以随时拼接在一起。


使用不可变数据结构,相应的等价物是什么?有没有一个名字?理想情况下,我希望步骤与可变情况下一样隔离但又可组合,在可变状态结构上具有天真的“叶代码”。


感兴趣的内容:MIT开放式课程持久化数据结构 - Guy Coder
1个回答

6

immuts的等价物是什么,它有一个名称吗?

我不知道是否有一个通用的子状态操作名称。但在Haskell中,有一个Lens提供了您所需的内容。

在C ++中,您可以将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};
};

您可以像这样编写基本镜头:

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 };
    }
};

注意,这个过程可以通过宏自动化。
然后,如果Bob包含immut<Alice>Alice包含immut<Charlie>,你可以编写2个镜头(从BobAlice和从AliceCharlie),BobCharlie的镜头可以组合成:
auto bob_charlie_lens = 
lens_composer(bob_alice_lens, alice_charlie_lens);

实时演示

注意:

下面提供了一个更完整的示例,其深度相关的内存增长是线性的,没有类型抹除开销(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";
}

啊,没事;你的实现是指数级的,但更紧凑的实现不会比二次方差(因为get随深度线性增长,而set复制了额外的get)。并且可以通过一些工作将其降低到线性开销。 - Yakk - Adam Nevraumont
1
一个无需宏定义的版本,使用operator|并且不需要为你操作的类型命名。链接 - Yakk - Adam Nevraumont
使用 operator->* 将镜头链到共享指针包装器上,以创建一种伪可变版本。 (我可能需要用这些来回答) - Yakk - Adam Nevraumont
@Yakk-AdamNevraumont 很有趣。但我认为转换运算符的“滥用”有点脆弱。你不能真正让attached_lens像普通值一样工作,因为在访问该值时需要显式地写出类型,这看起来比get()更尴尬。 - llllllllll
nod; 你可以将它写入一个(已定义类型的)变量中或者传递给函数。也可以重载 operator-> 来使用它。 - Yakk - Adam Nevraumont
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接