在 Mathematica 中定义自定义符号
我经常需要提取以将值列表限制为子列表,即如果 vals
给出 vars={x1,x2,x3,x4}
的值,并且我需要 vals
的值code>svars={x2,x4} 我确实 restrict[list,vars,svars]
restrict[vars_, svars_, vals_] :=
Extract[vals, Flatten[Position[vars, #] & /@ svars, 1]]
我想提高代码可读性,也许可以通过为 定义以下自定义表示法限制[vars,svars,vals]
(来源:yaroslavvb.com)
我的问题是
- 什么是实现这个的好方法吗?
- 这是一个好主意吗?
I often need to extract to restrict value lists to sublists, ie if vals
gives values of vars={x1,x2,x3,x4}
, and I need values of svars={x2,x4}
I do restrict[list,vars,svars]
where
restrict[vars_, svars_, vals_] :=
Extract[vals, Flatten[Position[vars, #] & /@ svars, 1]]
I'd like to improve code readability, perhaps by defining following custom notation for restrict[vars,svars,vals]
(source: yaroslavvb.com)
My questions are
- What is a good way to implement this?
- Is this a good idea altogether?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的符号可能非常有用 - 但我不确定是否需要这个特定的符号......
也就是说,
Notation
包使这变得非常简单。由于使用符号调色板时有很多隐藏框,我将使用屏幕截图:您可以看到通过使用
Action -> 底层
选项。在屏幕截图中的[4]中生成NotationMake*
downvalues 构造PrintNotationRulesGood notations can be very useful - but I'm not sure that this particular one is needed...
That said, the
Notation
package makes this pretty easy. As there are many hidden boxes when you use the Notation palette, I'll use a screenshot:You can see the underlying
NotationMake*
downvalues construct by using theAction -> PrintNotationRules
option. In[4] in the screenshot generates关于2:我将传递规则列表
Thread[vars -> vals]
而不是分别跟踪名称和值。我最喜欢的 Mathematica 习语之一是将规则列表与
WithRules
一起使用,如下定义:此构造计算With
块中的表达式,其中所有替换符号都已(递归地)定义)。这允许你做类似的事情,并让你在命名参数方面走得更远。
编辑:
WithRules
构造基于这两个 usenet 线程(感谢 Simon 挖掘它们):With regard to 2: I would pass the rule list
Thread[vars -> vals]
instead of keeping track of names and values separately.One of my favorite Mathematica idioms is to use rule lists together with
WithRules
as defined below: This construct evaluates an expression in aWith
block where all the replacement symbols have been (recursively defined). This allow you to do stuff likeand gets you quite far towards named arguments.
Edit: The
WithRules
construct is based on these two usenet threads (thanks to Simon for digging them up):