Hot answers tagged

28

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


20

Try this: Map[If[#==1,Unevaluated@Sequence[],#]&,{1,2,3}] Note the output. The 1 is gone. That's because Unevaluated@Sequence[] puts the empty sequence there, that is, "nothing". ##&[] is a shorthand that can be used in most places for same - ## is the sequence of arguments, & makes it a function to apply to something, [] is that something - ...


19

So recently I've learned from John Fultz that RawBoxes are kind of verbatim indicator for MakeBoxes which is not well stressed out in documentation. This or I've missed the point but it doesn't matter, here we have handy way to do this: x = 5; ToExpression @ MakeBoxes[RawBoxes["x"] = 123]; x 123


19

One way would be to redirect all messages issued by ToExpression to a string-stream. Here is an example of that approach, with minimal error-checking: Needs["Developer`"] interpret[str_String] := Module[{s = StreamToString[], r, m} , Block[{$Messages = {s}}, r = ToExpression[str, InputForm, HoldComplete]] ; m = StringFromStream[s] ; Close[s] ; ...


19

I know this has been answered already on this site, but I cannot seem to find it. Map and Apply do subtly different things. For example, Map[f, {a,b,c}] (* {f[a], f[b], f[c]} *) If you have a list that is more deeply nested, without using the third argument which is for level specification, you get Map[f, {{a,b}, {c}}] (* {f[{a,b}], f[{c}]} *) or, if ...


14

... why introduce Composition as a new feature? Composition is used to create a new anonymous function that can be used in all the standard ways such as Map and Apply etc. To achieve the same thing without it one needs a Function. Much like operator forms the use of Composition allows one to eliminate extraneous Function constructs which can make code ...


13

As djp explains parentheses are unnecessary in the FullForm of an expression; it is logical for superfluous information to be removed. However if you want parentheses to persist you could use something like this: $PreRead = # /. RowBox[{"(", body___, ")"}] :> RowBox[{"paren", "[", body, "]"}] &; MakeBoxes[paren[body___], form_] := ...


13

You can use the Notation package. It requires a GUI palette though. Needs["Notation`"] Once you have this package loaded, you can use the template to define: Notation[+[x___] ==> Plus[x___]] and then +[1,2,3] (* 6 *) Similarly, Notation[*[x___] ==> Times[x___]] and so *[2,3,4] (* 24 *) Note: A * typed as the first character of a cell ...


11

Intermingling Operator Forms & Linguistic Connections This answer attempts to draw out linguistic connections in understanding why operator forms seem so useful, a process that can perhaps point to further utility. Operator Forms are a type of modularization with the standard re-use and combinatory advantages but IMO the biggest benefit is cognitive - ...


9

The Notation package is not necessary to use an infix form of \[Star] as that is handled automatically. Also I recommend PadRight for constructing your expression (reference Generating a matrix using sublists A and B n times). SetAttributes[Star, HoldFirst] Star[a_List, n_Integer] := PadRight[a, n*Length@a, a] {1, 2}⋆5 (* ⋆ is \[Star] *) {1, 2, ...


9

Well, the following meets your formal requirements evenFunction[f_][args__] := f[Abs /@ Unevaluated[args]] evenFunction[even][a, b, c] even[Abs[a], Abs[b], Abs[c]] But is it really better than evenFunction[f_][args__] := f @@ Abs[{args}] I, myself, would choose the 2nd version over the 1st. Update It is not necessary to set the attribute ...


9

For Plus, there's this, from How would I add together any list of arguments as a pure function?: +Sequence[1, 2, 3] (* 6 *)


9

Imo the most common/readable/flexible way: Function[h, h[#, Log[#]] &][myF] /@ {7, 3} and for fun, less general, as pointed in comments: Through@*#[Identity, Log] &[myF] /@ {7, 3} which can be even shorter, thanks to ybeltukov Through@*#[# &, Log] &[myF] /@ {7, 3}


9

One can use Trace for this. I stuck in an extra, different error to show it is omitted in the output. It should also be clear how to trace other error messages. foo = Trace[ Table[ a = 1/0; b = {2, 3} c = i;, {i, 2}], HoldPattern@Message[Set::write, ___], TraceAbove -> True] (* Power::infty, Set::write errors *) If you would ...


8

As already explained, this happens because MatrixForm act as a wrapper. The answer to the question about how this behavior is implemented and how can eventually be reproduced is contained in the Informmation of the system symbol $OutputForms. Indeed ?? $OutputForms returns: $OutputForms is a list of the formatting functions that get stripped off ...


8

Also PlotRange[plot] PlotRange /. AbsoluteOptions[plot] Last @@ AbsoluteOptions[plot, PlotRange] PlotRange /. plot[[2]] all give (* {{0.,10.},{-0.999999,1.}} *) Note: Regarding usage of PlotRange as a function, it is undocumented, and the earliest reference I could find on this site is this answer dated Oct 11, 2012: The same range on each plot in a ...


8

You can make them an expression if you want. Let par[x.....] represent (x....). For example: (x+y)*z The FullForm would be: Times[par[Plus[x,y]], z] But in every such expression, the par[..] would only ever have on argument (in the example, Plus[x,y]). It would never modify the meaning of the argument. So in FullForm, there would be no point having ...


8

The documentation you linked to is more about how Infix is used to define output formats. You can find more information on how to use functions in infix form in the tutorials Special Ways to Input Expressions and Operator Input Forms. If you really want to use Partition in the infix form with an offset, you can use samplelist ~Partition~ Sequence[3, 2] ...


8

To summarize the comments into an answer: The second element is a list of lists because there may be several different tags sown. For example, Reap[Sow[1, x]; Sow[2, y]; result] (* {result, {{1}, {2}}} *) Another example by belisarius, Reap[Sow[1, {x, y}]; Sow[2, y]; Sow[3, x], _, tag] (* {3, {tag[x, {1, 3}], tag[y, {1, 2}]}} *) See also this ...


8

394 Unicode characters that are not valid Mathematica Symbols can be found from ss = Quiet@Table[{tem = "\\:" <> IntegerString[i, 16, 4], Symbol[tem]}, {i, 0, 16^4 - 1}]; notsym = Cases[ss, {z_, Symbol[__]} -> z] The list is largely but not entirely complete. To obtain the printable symbols for many of these unicodes, use ...


8

Simpler example: D[u', u] (* 0 & *) Usually it helps to inspect the FullForm of an expression to understand how Mathematica works. u' // FullForm But comparing the two similar forms, Derivative[1][u] and x[1][u], it's hard to understand what is happening. D[Derivative[1][u], u] // Trace D[x[1][u], u] // Trace D[x[1][u], u] /. x -> ...


8

Yes, you can use only pure functions: f = ## &[#, Log@#] & /* # &; f[myF] /@ {7, 3} (* {myF[7, Log[7]], myF[3, Log[3]]} *) It can be shorter with a bit different syntax: g = ## &[#, Log@#] &; g /* myF /@ {7, 3} (* {myF[7, Log[7]], myF[3, Log[3]]} *)


8

If you look at the FullForm of the expression {}, you see that you're not assigning "nothing", but an empty List: abc = {} is the same as abc = List[] That is, a List of zero length. {a, b, c, …} is merely syntactic sugar for List[a, b, c, …], so {} is syntactic sugar for List[]. What is a List? It's literally anything that has the Head List, so a ...


7

I believe it is important to get a fundamental understanding of what Pure Functions are that goes beyond the understanding using of a syntax. Hereafter an non-exhaustif summary of a few key understandings: 1) Pure Functions have they roots in Lambda calculus that forms the basis of functional programming paradigm implemented in Mathematica. 2) In ...


7

Unevaluated@Sequence[1, 2]~ConstantArray~10 $\ $ {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2} Or using Notation << Notation` Notation[ParsedBoxWrapper[ RowBox[{ RowBox[{"[", "const_", "]"}], "\[Star]", "reps_"}]] \[DoubleLongRightArrow] ParsedBoxWrapper[ RowBox[{ RowBox[{"Unevaluated", "@", RowBox[{"Sequence", "[", "const_", ...


7

Look at the Possible Issues section of the documentation for Sort: "Numeric expressions are sorted by structure as well as numerical value" list = {1/2 (1 + Sqrt[5]), 1, 1, 1/2 (1 - Sqrt[5]), 0}; The approach recommended there to Sort by numerical value only is sorted = Sort[list, Less] (* {(1/2)*(1 - Sqrt[5]), 0, 1, 1, (1/2)*(1 + Sqrt[5])} *) ...


7

Module[{i = 1}, Nest[1 + x^n (#) &, 1, 3] /. n :> i++] Or (same result) Fold[1 + x^#2 #1 &, 1, {3, 2, 1}]


7

How about this?: Evaluate@Grad[#1 + #2^2, {#1, #2}] & (* {1, 2 #2} & *) Or for pure obfuscatory fun: I'd like to reinstate to my first answer (see edit history), Evaluate@Grad[#1 + #2^2 &[#1, #2], {#1, #2}] & even though #1 + #2^2 &[#1, #2], which equals #1 + #2^2 and seemed redundant, because it has the right general form, ...


6

If you cannot resolve the keyboard behavior try an alternate input form; I propose: EscdinttEsc To input: Then use Tab to move between the Placeholder fields.


6

Range[10] - Make a list of integers from 1 to 10. /. - Replace all occurrences of {x_ - anything, to which we will refer to as x /; - so long as the test PrimeQ[x] - for primality yields True -> - with x^2} - the square of itself.



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