假设我有一个不可变的包装器:
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; } ); };
}
所以如果Bob是int 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;
步骤可以在需要的地方缝合在一起。
immuts 的等价物是什么,它有名称吗?理想情况下,我希望这些步骤既独立又可组合,就像在可变情况下一样,天真的“叶代码”位于可变状态结构上。
最佳答案
What is the equivalent with immuts, and is there a name for it?
IDK 是否存在子状态操作的通用名称。但是在 Haskell 中,有一个 Lens 它提供的正是您想要的。
在 C++ 中,您可以考虑 lens作为一对 getter 和 setter 函数,它们都只关注其直接子部分。然后有一个 Composer 将两个镜头组合在一起,专注于结构的更深层次。
// 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个镜头( Bob 到 Alice 和 Alice 到 Charlie ),Bob至 Charlie镜头可以由以下组成:
auto bob_charlie_lens =
lens_composer(bob_alice_lens, alice_charlie_lens);
注意:
Below是一个更完整的示例,具有线性内存增长 w.r.t 深度,没有类型删除开销(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";
}
关于c++ - 修改不可变子结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53699946/
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:
最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路
您将如何构建一个简单的Sinatra应用程序?我正在制作,我希望该应用具有以下功能:“应用程序”更像是一个包含所有信息的管理仪表板。然后另一个应用程序将通过REST访问信息。我还没有创建仪表板,只是从数据库中获取东西session和身份验证(尚未实现)您可以上传图片,其他应用可以显示这些图片我已经使用RSpec创建了一个测试文件通过Prawn生成报告目前的设置是这样的:app.rbtest_app.rb因为我实际上只有应用程序和测试文件。到目前为止,我已经将Datamapper用于ORM,将SQLite用于数据库。这是我的第一个Ruby/Sinatra项目,所以欢迎任何和所有建议-我应
我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我
我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“
我想编写一个ruby脚本来递归复制目录结构,但排除某些文件类型。因此,给定以下目录结构:folder1folder2file1.txtfile2.txtfile3.csfile4.htmlfolder2folder3file4.dll我想复制这个结构,但不包含.txt和.cs文件。因此,生成的目录结构应如下所示:folder1folder2file4.htmlfolder2folder3file4.dll 最佳答案 您可以使用查找模块。这是一个代码片段:require"find"ignored_extensions=[".cs"
有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=