我经常需要提取以将值列表限制为子列表,即如果 vals
给出 vars={x1,x2,x3,x4}
的值,我需要svars={x2,x4}
的值我做 restrict[list,vars,svars]
where
restrict[vars_, svars_, vals_] :=
Extract[vals, Flatten[Position[vars, #] & /@ svars, 1]]
我想提高代码的可读性,或许可以通过为 restrict[vars,svars,vals]
定义以下自定义符号来提高代码的可读性
(来源:yaroslavvb.com)
我的问题是
- 什么是实现它的好方法?
- 这完全是个好主意吗?
最佳答案
好的符号可能非常有用 - 但我不确定是否需要这个特别的符号......
就是说,Notation
包让这一切变得非常简单。由于使用 Notation 调色板时有很多隐藏框,我将使用屏幕截图:
您可以使用 Action -> PrintNotationRules
选项查看底层的 NotationMake*
downvalues 构造。在[4]中截图生成
NotationMakeExpression[
SubscriptBox[vals_, RowBox[{vars_, "|", svars_}]], StandardForm] :=
MakeExpression[
RowBox[{"restrict", "[", RowBox[{vars, ",", svars, ",", vals}],
"]"}], StandardForm]
NotationMakeBoxes[Subscript[vals_, vars_ | svars_], StandardForm] :=
SubscriptBox[MakeBoxes[vals, StandardForm],
RowBox[{Parenthesize[vars, StandardForm, Alternatives], "|",
Parenthesize[svars, StandardForm, Alternatives]}]]
关于wolfram-mathematica - 在 Mathematica 中定义自定义符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4190845/