我该如何优化这个?
我目前正在学习编写 Erlang 代码。我在 Chicago Boss 之上有一个网络应用程序。 我有一个名为 Todo 的模型,我想在其上提供 CRUD 操作作为 REST API。
在我的 PUT 方法中,我有以下代码:
index('PUT', [Id]) ->
Todo = boss_db:find(Id),
Body = element(2, mochijson:decode(Req:request_body())),
%% Set the new values
NewTodo = Todo:attributes([
{subject, proplists:get_value("subject", Body)},
{done, proplists:get_value("done", Body)}
])
,
{json, [{todo, element(2, NewTodo:save())}]}.
如何优化此代码片段?或者这已经是最好的了吗?
是否有一些“更智能”的方法可以将 proplist 的键更改为原子键?像这样:
[{"subject", "Foo"}] -> [{subject, "Foo"}].
我还发现分配一个 Todo 变量然后再创建一个 NewTodo 有点乏味。遗憾的是,我在 github 上找不到一些好的 Erlang Chicago Boss 应用程序示例可供查看。
I'm currently learning to code Erlang. I have a web application on top of Chicago Boss.
I have a model called Todo, and I would like to offer CRUD operations on it as a REST API.
In my PUT method I have this code:
index('PUT', [Id]) ->
Todo = boss_db:find(Id),
Body = element(2, mochijson:decode(Req:request_body())),
%% Set the new values
NewTodo = Todo:attributes([
{subject, proplists:get_value("subject", Body)},
{done, proplists:get_value("done", Body)}
])
,
{json, [{todo, element(2, NewTodo:save())}]}.
How can I optimize this code fragment? Or is this already the best possible?
Is there some "smarter" way to change the keys of a proplist to atom keys? Like this:
[{"subject", "Foo"}] -> [{subject, "Foo"}].
I also find it kind of tedious to assign a Todo variable and then have a NewTodo. Sadly I can't find some good example Erlang Chicago Boss apps on github that I can check out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你总是可以做这样的事情:
但我怀疑,在你的情况下,这会显着提高速度。
也许你能够从中挤出最后一点:
这仅对基准代码竞赛有价值;-)(注意最后一个子句中没有
lists:reverse/1
调用。这会破坏改进 PS:如果您认为我是微优化狂,那么您是对的,所以我将用lists:reverse/2
替换
lists:reverse/1
调用code>直接使用BIF并保存再多一些时间;-)You always can do something like this:
But I doubt, it will be significant speed improvement in your case.
May be you will be able squeeze last bit from this:
Which is worth only for benchmark code competitions ;-) (Note there is not
lists:reverse/1
call in last clause. It would be ruining improvement form previous version.)P.S.: If you think I'm micro-optimization freak, you are right, so I would replace
lists:reverse/1
call withlists:reverse/2
to use BIF directly and save some more time ;-)不幸的是,我无法评论 Hynek 的答案,但作为 Erlang 新手,我的第一个猜测是按照以下方式进行操作:
lists:map(fun({A, B}) -> {list_to_atom(A ), B} end, [X || {Y, Z}=X <- List, is_list(Y)]).
你无法真正避免 NewTodo 赋值
Unfortunately I cannot comment on Hynek's answer, but as Erlang newbie, my first guess would have been to go for something along the lines of:
lists:map(fun({A, B}) -> {list_to_atom(A), B} end, [X || {Y, Z}=X <- List, is_list(Y)]).
You cannot really avoid the NewTodo assignment
怎么样
How about