2010-11-16 81 views
2

我經常需要提取限制值列表,以子列表,也就是說,如果vals給出vars={x1,x2,x3,x4}值,我需要的svars={x2,x4}值我做restrict[list,vars,svars]其中自定義符號問題

restrict[vars_, svars_, vals_] := 
Extract[vals, Flatten[Position[vars, #] & /@ svars, 1]] 

我想提高代碼可讀性,或許通過定義restrict[vars,svars,vals]

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

下面的自定義符號我的問題是

  1. 什麼是一個很好的實現方法?
  2. 這是一個好主意嗎?

回答

4

良好的符號是非常有用的 - 但我不知道,這個特殊的需要......

這就是說,Notation包使得這很容易。由於當您使用符號調色板有很多隱藏的箱子,我將使用一個屏幕截圖:alt text

你可以看到底層NotationMake* downvalues使用Action -> PrintNotationRules選項構建。在[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]}]] 
+0

相關的問題,怎麼辦我得到Notation Palette?我在其中一個教程中找到了一個鏈接,但它不在我的調色板菜單 – 2010-11-17 01:19:17

+0

提供'Notation'AutoLoadNotationPalette == True',它應該在需要[「Notation'」]時自動打開。如果沒有,那麼你可以從ToFileName [{$ InstallationDirectory,「AddOns」,「Packages」,「Notation」,「LocalPalettes」,「English」},「」]'打開它並/或者從調色板菜單。 – Simon 2010-11-17 02:56:24

3

關於2:我將通過保持跟蹤的名稱和值的單獨的規則列表Thread[vars -> vals]代替。
我最喜歡的Mathematica成語之一是將規則列表與WithRules一起使用,如下所定義的:此構造評估所有替換符號已被遞歸定義的With塊中的表達式。這可以讓你做類似於

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

並且讓你對命名參數很有幫助。

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

編輯:WithRules結構是基於這兩個新聞組線程(感謝西蒙挖起來):

+0

它類似於http://stackoverflow.com/questions/4152194/automatically-generating-sums-in-mathematica/4152797#4152797。 IE,我通過x1,x2,x3求和f1(x1,x2)* f2(x2,x3),其中fi的參數存儲在args [fi] – 2010-11-16 04:10:41

+1

好的,所以這可能沒那麼有用。不過,這是我最喜歡的技巧,所以任何藉口都會發布它:) – Janus 2010-11-16 04:36:11

+0

這是一個不錯的訣竅。我記得在[此數學論壇帖子]中討論過類似的方法(https://groups.google.com/group/comp.soft-sys.math。數學/ browse_thread /線程/ 6fa6b0ad9d5d111c)。 – Simon 2010-11-16 05:51:42