Tag Info

Hot answers tagged

66

What this answer is and is not To avoid some confusion and misunderstanding, let me state right away what is the intended status of this answer. This answer is not A tutorial to the subject A systematic, or complete, introduction to the subject An authoritative answer putting the final word on the subject This answer hopefully is An (subjective!) ...


21

Use pure functions (Function) and "InlineExternalDefinitions" -> True: g = #^2 &; f = # + 1 &; compiledFunction = Compile[{{x, _Real, 0}}, f@g[x], CompilationOptions -> {"InlineExternalDefinitions" -> True}]; CompilePrint[compiledFunction] 1 argument 1 Integer register 4 Real registers Underflow ...


20

Yes there is a way to use functions that use external non compiled functions. It uses the step function of Mr.Wizard defined in the post How do I evaluate only one step of an expression?, in order to recursively expand the code that we want to compile until it uses only functions that Mathematica can compile. The technique discussed in the post How to ...


18

That's an interesting first question. Welcome. :-) From a simplistic perspective this should work, but as you observe there are evaluation properties that are more complex. Here is a reference for most (but not all) behavior: The Standard Evaluation Sequence Let's follow those steps for your example. Heads are evaluated first Evaluate the head h of ...


16

Implementation The following implementation is based on expression serialization and SequenceAlignment built-in function. The idea is to break expressions into constituent parts, then align these part sequences, and then determine the positions where the expressions are different. The auxiliary heads we will need are inert heads diff and myHold, the latter ...


16

This is a tricky case indeed, because what you basically ask for is compile-time evaluation (macro-style). Generally, the answer is to use meta-programming, to assemble the compiled expression at run-time. The reason your attempt did not work is that the expression you want to evaluate is too deep for Evaluate to be effective. Solution using in-place ...


14

Ok, what you have here is some classic example of what is called "Evaluation leaks". So, first, the corrected code: ClearAll[capture] SetAttributes[capture, HoldAllComplete]; capture[expr_ /; AtomQ[Unevaluated[expr]]] := {Head[Unevaluated[expr]], expr}; capture[head_[args___]] := {head, capture /@ Unevaluated[{args}]}; Now, you can inspect it and ...


13

Here I offer the safe version of Get that can be used successively to collect all the source files and contexts of packages without polluting the memory (too much). What it does I have practically reverse-engineered all the necessary functions (Get, Needs, BeginPackage, Begin, EndPackage and End) so that I could inject the monitoring code for ...


9

If your definitions are exactly like you show, every time, you can use belisarius's method, slightly refined: g[x_Integer] := x + 1 g[s_String] := s <> "!!!" (DownValues@g)[[All, 1, 1, 1, 2, 1]] {Integer, String} However this is fragile in that it will fail if your definitions are different, e.g.: g[r_ /; Head[r] === Real] := r + Pi ...


8

Ad Hoc Programming: Notebooks It is very common for programming problems to be solved completely without leaving the confines of a single notebook. A notebook can contain any combination of function definitions and expressions that use those functions. See, for example, the Function Definitions section of the Fast Introduction For Programmers. The nicest ...


7

Not an answer per se, but two clarifications (which are too long for the comment box): 1) The Wiki definition you have linked to for a narcissistic number is not really apt. The Wiki page is actually describing the definition for an Armstrong Number, also known as pluperfect digital invariants, or m-narcissistic numbers, such as: $$407 = 4^3 + 0^3 + 7^3$$ ...


7

Evaluate will solve this. F[x_] := x + 2; G[x_] := x; ff = Compile[{x}, Evaluate@F[G[x]]]; <<CompiledFunctionTools` CompilePrint@ff result 1 argument 1 Integer register 2 Real registers Underflow checking off Overflow checking off Integer overflow checking on RuntimeAttributes -> {} ...


7

Here is a functional approach: Narciss[x_] := With[{num = IntegerDigits[x]}, Total[num^Length[num]] == x] Here is a compiled version of the above function: NarcissC = Compile[{{x, _Integer}}, With[{num = IntegerDigits[x]}, Total[num^Length[num]] == x], Parallelization -> True, CompilationTarget -> "C", RuntimeAttributes -> Listable, ...


7

This also works: getHeads[g_] := DownValues[g][[All, 1, 1, 1]] /. Verbatim[Pattern][_, k_] :> k[[1]] Then: getHeads[g] {Integer, String}


7

With this helper function: SetAttributes[partThread, HoldAll]; partThread[l___, rhs_] := Join @@ Replace[ MapIndexed[Append[#, First@#2] &, Thread[Hold[{l}]]], Hold[s_, i_] :> Hold[s = rhs[[i]]], {1}]; The following modification of LetL seems to work according to your specs: ClearAll[Let, let]; SetAttributes[{Let, let}, HoldAll]; ...


6

If you can convert expressions to text form, there's a possible answer here. I sometimes use it to compare notebooks: notebook1 = StringJoin[ Import["/tmp/freaky-illusion.nb", "Plaintext"]]; notebook2 = StringJoin[ Import["/tmp/freaky-illusion-1.nb", "Plaintext"]]; System`Dump`showStringDiff[notebook1, notebook2]


6

I'm not sure what you're trying to do here and most probably Nasser's admonition rings true, but perhaps you want something like this?: Do[ CellPrint @ Cell[BoxData[RowBox[{RowBox[{"r", "[", i, "]"}], "="}]], "Input"], {i, 5} ] Alternatively you might make use of \[Placeholder] and Defer: Do[CellPrint @ ExpressionCell[Defer[r[#] = \[Placeholder]], ...


5

This question is closely related to: Best practice of passing a large number of parameters to functions In my answer there I gave a couple of abstractions to simplify definitions of the type you describe. I shall reiterate my approach with adjustment for your syntax. Code using listWith SetAttributes[{listWith, defWithOpts2}, HoldAll] listWith[(set : ...


5

Please be gentle with me - this is my first ever post to stackexchange. Firstly, I'd like to say that I found Faysal's post both fascinating and outstandingly useful (I would upvote it if I could, but I have insufficient reputation). It introduces techniques I'm sure I shall use a great deal. However, it doesn't, quite, cater for all use cases. Where a ...


5

f[g_] := Cases[First[#], Verbatim[Blank][x_] :> x, ∞] & /@ DownValues[g]


4

Dynamically generated Do loops:) cnar = With[{n = 7}, With[{var = Array[Unique["x"] &, n]}, With[{n1 = FromDigits@var, n2 = Total[var^n]}, Compile[{Null}, Do[If[n1 == n2, Sow@n1], ##], RuntimeOptions -> "Speed", CompilationTarget -> "C" ] & @@ MapAt[1 &, Thread[{var, 0, 9}], {1, 2}] ] ] ]; ...


4

nar[m_] := ToExpression[ "Compile[{$},Do[With[{n=0" <> StringJoin[ Table["+1" <> Array["0" &, m - 1 - i, 1, StringJoin] <> "a" <> ToString[m - 1 - i], {i, 0, m - 1}]] <> ",n2=0" <> Table["+a" <> ToString[m - 1 - i] <> "^" <> ToString[m], {i, 0, m - 1}] <> ...


4

From a cold start, I would have written it like this: findNarc = Compile[{{stop, _Integer}, {pow, _Integer}}, Do[ If[Total[IntegerDigits[n]^pow] == n, Sow[n]] , {n, 1, stop} ] , RuntimeOptions -> "Speed", CompilationTarget -> "C"]; However, it is slower than your function (which takes 0.326 seconds on my machine) ...


4

Following belisarius comment you could do something like Function[z, z = f /@ z, HoldFirst]@{x, y} So you put the Map operation inside the pure function. E.g. x = {1, 2, 3}; y = {4, 5, 6}; f = #1 + 1 &; Function[z, z = f /@ z, HoldFirst][{x, y}]; x y seems to work.


4

I'm guessing the OP is looking a way to generate a number of indexed assignments from a list of data elements. If so, then maybe something like the following will work for the OP: Clear[data, r]; data = RandomInteger[{0, 99}, 5]; MapIndexed[(r[#2[[1]]] = #) &, data]; ?r Global`r r[1]=14 r[2]=95 r[3]=39 r[4]=26 r[5]=60


4

Other solutions: f2 = "Compile[{{arr,_Real,2}}, Module[{a,b,c,d},{a,b,c,d}=arr;" <> ToString[ InputForm@ Map[Mean, Partition[Tuples[{a, b, c, d}, 2], 4], {2}]] <> "],RuntimeAttributes->{Listable}]" // ToExpression; f3 = Compile[{{arr, _Real, 2}}, Module[{a, b, c, d}, {a, b, c, d} = arr; #], ...


4

I'm not to present any thorough analysis if metaprogramming is viable, but I could give a hint towards this issue. I don't think there is any fundamental barrier for metaprogramming in Mathematica, but I doubt we could develop this way anything really powerful. To point out a practical obstacle (though by any means not a no-go theorem) I suggest to take a ...


4

Well, one obvious idea would be to build on the struct implementation by Bob Beretta. You would have to add information about methods and modify the implementation of --> to consider those as well, and for polymorphism, you'd also have to store the base class (or base classes, if multiple inheritance should be supported), and have --> look there if the ...


3

A very useful idiom for avoiding evaluation leaks is: foo= Function[{expr, pattn, levels}, Extract[Unevaluated[expr], Position[Unevaluated[expr], pattn, levels], HoldComplete], {HoldAllComplete}] This function foo finds parts of expr at specified levels that match pattn and most important it wraps them in HoldComplete before they get a chance to ...


3

For diff'ing code fragments/expressions, you can copy-and-paste as "Plain Text" into Quick Diff (online) or into WinMerge (PC-based), ref. http://stackoverflow.com/q/15655828/879601 (also mentions a Mac-based method using Bash). E.g. WinMerge:- (For diff'ing packages and notebooks I favour CSDiff.)



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