Tag Info

Hot answers tagged

44

Point #1 Part always wraps element sequences with the original head of the expression. expr = Hold[1 + 1, 2 + 2, 3 + 3, 4 + 4, 5 + 5]; expr[[{2, 3}]] Hold[2 + 2, 3 + 3] For this purpose a single part e.g. 1 is not a sequence but {1} and 1 ;; 1 are: expr[[1]] expr[[{1}]] expr[[1 ;; 1]] 2 Hold[1 + 1] Hold[1 + 1] This applies at every level ...


41

One convenient way to think of Flatten with the second argument is that it performs something like Transpose for ragged (irregular) lists. Here is a simple example: In[63]:= Flatten[{{1,2,3},{4,5},{6,7},{8,9,10}},{{2},{1}}] Out[63]= {{1,4,6,8},{2,5,7,9},{3,10}} What happens is that elements which constituted level 1 in the original list are now ...


38

A second list argument to Flatten serves two purposes. First, it specifies the order in which indices will be iterated when gathering elements. Second, it describes list flattening in the final result. Let's look at each of these capabilities in turn. Iteration Order Consider the following matrix: $m = Array[Subscript[m, Row[{##}]]&, {4, 3, 2}]; $m ...


36

square = Function[x, x^2]; square1 = #^2 &; square2[x_] := x^2; DownValues[square] DownValues[square1] DownValues[square2] {} {} {HoldPattern[square2[x_]] :> x^2} Two differences that immediately come to mind are that: 1) functions with down values won't autocompile when you use them in Table, Map, Nest etc. so therefore are less efficient when ...


31

It is used in TraditionalForm output, e.g. here: TraditionalForm[ Hypergeometric2F1[a,b,c,x] ] Without \[InvisibleApplication] it would probably be hard for Mathematica to parse it back to InputForm. Probably it is used in more places internally. In order to get rid of it: Locate the file UnicodeCharacters.tr in ...


31

There is no way to comment out a single line. Mathematica doesn't really respect lines, it pushes working at the expression level when possible (not at the source text level). Converting cells between different forms (StandardForm, InputForm) will even shuffle around newlines. Copying and pasting code does the same. As @acl has menioned, you can select a ...


30

Compose and Composition There is, but it is deprecated (in favor of Composition): Compose: MapThread[Compose, {{a, b, c}, {1, 2, 3}}] (* {a[1], b[2], c[3]} *) I still use Compose myself, but I would not take the responsibility to recommend this as a common practice. You can also use Composition[#1][#2] &, although this is hardly better than your ...


29

Between Versions 7 and 8 Hash now gives the hash of a raw sequence of characters when applied to Strings. In past versions the string characters (quotation marks) were included in the calculation of the hash. (Reference) Use "\"" <> string <> "\"" before hashing if you want output to match older versions. \[Dash], \[LongDash] and ...


28

For me the operator forms of Map and Apply will probably provide the most important benefits in terms of code readability. Often I need to apply a sequence of transformations to some data, and I am fond of infix notation for this purpose. For example I find a ~Position~ 0 ~SortBy~ Last more readable than the "conventional" SortBy[Position[a, 0], Last] ...


25

It is a good habit to get into because you can often get tripped up by precedence rules (no one remembers everything!). For instance, PatternTest binds very tightly. See the difference between these two definitions: Clear@f f[_?(# == 2 &)] := Print@"foo" f[_] := Print@"bar" f[2] (* "foo" *) Clear@g g[_?# == 2 &] := Print@"foo" g[_] := Print@"bar" ...


22

The default value of $NumberMarks Automatic means that ` should by default be used in arbitrary-precision but not machine-precision numbers. Arbitrary-precision numbers can contain an arbitrary number of digits e.g. : Sqrt[3`21] == 1.73205080756887729353 Machine numbers contain the same number of digits and maintain no information on their ...


21

Because PatternTest binds very tightly. You need extra parentheses: MatchQ[3, _?(Composition[Not, OptionQ])]


21

As explained by Michael Pilat you cannot create your own compound operators with custom precedence. (You could conceivably write your own parser as Leonid has worked on, or attempt to coerce the Box form with CellEvaluationFunction.) You can however use an existing operator with the desired precedence. Looking at the table Colon appears to be a good ...


21

I like to use Ctrl+. to discover how it's grouped. For example, in this example: Plot3D[Sin[x y], {x, 0, 3}, {y, 0, 3}, ColorFunction -> Hue[#] &] Putting your cursor position after & and pressing Ctrl+. two times, you will get all expression ColorFunction -> Hue[#] marked, so it's wrong, and you need to put () like this: Plot3D[Sin[x y], ...


20

In addition to Brett's counter-example, it might be helpful to view this from Mathematica's philosophy, which is "everything is an expression". In this framework, you're not really indexing a 1D/2D array, but you're extracting a Part from an expression. Indeed, you can use the ⟦ ⟧ notation on any expression, not just lists/matrices. For example: Sin[x + ...


20

I suggest an approach based on creating lexical and / or dynamic environments (custom scoping constructs if you wish), inside which the rules of our "universe" will be altered. I will illustrate with a dynamic environment: ClearAll[withStringManipulations]; SetAttributes[withStringManipulations, HoldAll]; withStringManipulations[code_] := ...


20

These two forms may be similar on the surface, but they are very different in terms of the underlying mechanisms invloved. In a sense, Function represents the only true (but leaky) functional abstraction in Mathematica. Functions based on rules are not really functions at all, they are global versions of replacement rules, which look like function calls. ...


19

Your code reveals exactly why Clear complains: Subscript[x, r] is not a Symbol nor a String. When you assign a value to it, you're setting a DownValue not an OwnValue; in other words, you're setting the value of a function not a variable. To use $x_r$ as a symbol, use the Notation` package's function, Symbolize. I'd recommend using it from the palette ...


19

As the error message indicates Clear does not work that way. There are several assignment forms that automatically create a definition to something other than a raw symbol: x[5] = 1; Subscript[x, 1] = 2; x /: Subscript[x, 2] = 3; N[x] = 3.14159; DownValues[x] DownValues[Subscript] UpValues[x] NValues[x] {HoldPattern[x[5]] :> 1} ...


19

Maybe I miss the point here, but FullForm[x ↗ y] gives UpperRightArrow[x,y]. This is described in the documentation to UpperRightArrow and since this symbol is not protected and has not built-in meaning, you can just define it the way you like: UpperRightArrow[x_, y_] := FooBar[x, y] and this instantly gives you Update: As answer to Jacobs ...


18

The backtick is a short-hand to mark the precision of your output. If it is not followed by any number, it denotes machine precision. You can denote arbitrary precision by including a number, as for example, 0.3`20. By default, these are not displayed in StandardForm, which is why you see them only when copying, at which point it gets converted to ...


18

To programmatically find the internal representation of the shortforms, you can use MakeExpression, which gives the result wrapped in HoldComplete. Here's an example: MakeExpression@"?name" (* HoldComplete[Information["name", LongForm -> False]] *) MakeExpression@"??name" (* HoldComplete[Information["name", LongForm -> True]] *)


18

To understand what's happening, the difference between evaluation and parsing needs to be made clear: parsing means taking the string (the text) input to Mathematica and converting it to some internal representation of a Mathematica expression evaluation means taking a Mathematica expression and transforming it according to some rules the evaluator knows ...


18

Functions are more concise and generally faster but patterns are a lot more expressive. When you don't need the expressive power of patterns you should probably use functions. I use down values more to set up the high level structure of my program and functions to implement the algorithms. But often I am lazy and use down values out of habit. When I am in ...


18

Here is my version using injector pattern: ClearAll[myWith]; SetAttributes[myWith,HoldAll]; myWith[pars_=vals_,body_]:= Apply[Set,Hold[Evaluate[Transpose[{pars,vals}]]],{2}]/. Hold[vars_]:>With[vars,body] This code assumes that pars evaluate to a list of symbols. For example, myWith[params=vals,a+b+c+d] (* 10 *)


17

I don't think that invisible characters have any internal uses. They are probably just to make expressions look nice to us humans. The place I can think of using \[InvisibleApplication] is as some group action g x = g[x], but there are sure to be other places. As for making invisible characters visible. You can make all special characters explicit using ...


17

It is probably debatable to what extent it has built-in object oriented features. In any case, this answer is not intended to lead you to try to emulate object oriented programming, which is in general a bad idea. (see @Leonid 's answer) However, it is not debatable that Mathematica is tremendously flexible (as to style and notation at least, the evaluation ...


17

At the risk of repeating myself, I would like to stress that one has to be critical towards the superficial flexibility offered by Mathematica, when (particularly mutable) data structures are concerned. Using mutable data structures assumes a programming style for which Mathematica is not optimized. It can emulate it, yes, and we have seen a number of such ...


17

I would have liked to have more experience with the operator forms before this question was asked as I am short on examples, and I'm sure my opinion will evolve over time. Nevertheless I think I have enough familiarity with similar syntax to provide some useful comments. Taliesin Beynon provided some background for this functionality in Chat: Operator ...


16

No. For example, functions do not have to be atomic. It can be possible to extract parts from them (although it's generally not recommended.) In[1]:= if=Interpolation[Range[10]^2] Out[1]= InterpolatingFunction[{{1,10}},<>] In[2]:= if[3] Out[2]= 9 In[3]:= if[[3]] Out[3]= {{1,2,3,4,5,6,7,8,9,10}}



Only top voted, non community-wiki answers of a minimum length are eligible