Custom Notation question

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]

http://yaroslavvb.com/upload/custom-notation.png

My questions are

  • What is a good way to implement this?
  • Is this a good idea altogether?

  • Good 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 the Action -> PrintNotationRules option. In[4] in the screenshot generates

    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]}]]
    

    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 a With block where all the replacement symbols have been (recursively defined). This allow you to do stuff like

    WithRules[{a -> 1, b -> 2 a + 1}, b]
    

    and gets you quite far towards named arguments.

    SetAttributes[WithRules, HoldRest]
    WithRules[rules_, expr_] := Module[{notSet}, Quiet[
         With[{args = Reverse[rules /. Rule[a_, b_] -> notSet[a, b]]},
           Fold[With[{#2}, #1] &, expr, args]] /. notSet -> Set, 
       With::lvw]]
    

    Edit: The WithRules construct is based on these two usenet threads (thanks to Simon for digging them up):

  • A version of With that binds variables sequentially
  • Add syntax highlighting to own command
  • 链接地址: http://www.djcxy.com/p/35536.html

    上一篇: 自动保存笔记本(或mathematica中的其他类型文件)文件

    下一篇: 自定义符号问题