eval in function scope (accessing function args)

 ̄綄美尐妖づ 提交于 2019-12-02 09:48:08

Don't use eval! In almost all cases, unless you really know what you're doing, you shouldn't be using eval. And in this case, eval simply won't work because it operates in the global (or module) scope and doesn't have access to the variables local to the function (like the argument gene).

While the code you posted isn't quite enough for a minimal working example, I can take a few guesses as to what you want to do here.

Instead of map(x->("mutate_copy(gene.$x)"),all_fields_except_score), you can dynamically look up the field name:

map(x->mutate_copy(gene.(x)), all_fields_except_score)

This is a special syntax that may eventually be replaced by getfield(gene, x). Either one will work right now, though.

And then instead of eval(parse("$(T)("*join(all_fields_except_score,",")*")")), call T directly and "splat" the field values:

T(all_fields_except_score...)

I think the field order should be stable through all those transforms, but it looks a pretty fragile (you're depending on the score being the last field, and all constructors to have their arguments in the same order as their fields). It looks like you're trying to perform a deepcopy sort of operation, but leaving the score field uninitialized. You could alternatively use Base's deepcopy and then recursively set the scores to zero.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!