# Tag Info

47

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

46

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

45

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

39

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

39

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

36

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

35

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

33

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

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

27

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

27

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" ...

26

Clearly the @ notation is inspired by the usual mathematical notation for function composition. f@g[x] looks very similar to the mathematical notation $(f\circ g)(x)$. But it is important to understand that @ does not denote function composition. In mathematical notation $f\circ g$ is also a function. In Mathematica f@x is simply a different way to ...

24

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

24

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

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[321] == 1.73205080756887729353 Machine numbers contain the same number of digits and maintain no information on their ... 22 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_] := ... 22 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], ... 21 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 ... 21 # is a placeholder for an expression. If you want to define a function,$y(x)=x^2\$, you just could do: f = #^2 & The & "pumps in" the expression into the # sign. That is important for pairing & and # when you have nested functions. f[2] (* 4 *) If you have a function operating on two variables, you could do: f = #1 + #2 & So ...

21

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

21

Good News Everyone! Two-parameter syntax for Fold and FoldList has been (silently) implemented! Taliesin Beynon informs me that this was implemented in 2011, so check your older versions as well. As Naitree notes this is now documented in 10.0.2: Fold[f, a] FoldList[f, a] f[f[f[1, 2], 3], 4] {1, f[1, 2], f[f[1, 2], 3], f[f[f[1, 2], 3], 4]} And ...

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

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

20

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 *)

20

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

19

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.320. By default, these are not displayed in StandardForm, which is why you see them only when copying, at which point it gets converted to ...

19

References and intro First, let me point out that = is shorthand for Set and := for SetDelayed; this facilitates searching the docs. Also, as Simon Woods points out in a comment to the question, there is a tutorial on this. Explanation The basic distinction is this: y[x_]=expr means evaluate expr, then whenever you see y[something] evaluate evaluate what ...

19

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

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

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