Hot answers tagged

36

Here is my attempt to generate a pseudocode for algorithmicx package. Current features Functions (as SetDelayed) Set If with 2 and 3 arguments While Do (any number of variables of any type) New! Return Module, With, and Block CompoundExpression (;) Test functions (EvenQ, etc., and Not@EvenQ, etc.) New! Indentation Code ClearAll[pseudocode, pscd] ...


33

Leonid provides a nice method for doing this within "pure functions" but I think it should be pointed out that the common method for doing this is pattern matching. I argue that destructuring is the foundational use of pattern matching in Mathematica. Every replacement pattern, be it an explicit rule (:>, ->) or part of a definition (:=, =), that ...


17

You can use macros / code generation to be able to use the syntax you like. Here is one possibility: ClearAll[withLiteralIndices]; SetAttributes[withLiteralIndices, HoldAll]; withLiteralIndices[code_, inds : {__Symbol}] := Block[inds, Unevaluated[code] /. MapIndexed[ Function[{i, pos}, pos /. {p_} :> (i :> #2[[p]])], ...


14

I think Mr. Wizard provided a very thorough answer to the question. I would however like to add a slight example of wrapping this up nicely in a format similar to Function[] but using destructuring: SetAttributes[dFunction, HoldAll] dFunction[pattern_, body_][arg___] /;MatchQ[{arg}, pattern] := {arg} /. pattern :> body This then allows you to have nice ...


12

One use case that I've been exploring has been to replace Mathematica's own Compile functionality with (potentially much faster) generated C which can be compiled using CCompilerDriver` and linked back in using LibraryFunctionLoad. The built-in Compile is a very nice piece of functionality, but if you examine the generated C output for many ...


11

Check the CUDALink/OpenCLLink documentation, they have some creative applications http://reference.wolfram.com/mathematica/CUDALink/tutorial/Applications.html#818090 http://wolfram.com/xid/0isq3flowdud5n74bny881he6-0wsz71 http://wolfram.com/xid/0d195cdqgdtuw44ioyvm6og9pu-bv64sq Also the webinars have other examples.


11

ToCCodeString has the "Indent" option, which defaults to None. Set it to the number of tabs you want for an indentation, and you should be fine.


11

I think, your question is as much about techniques of evaluation control, as it is about code generation. I will show several different methods to achieve the first result you asked for, which would illustrate different approaches and techniques of evaluation control. Working with unevaluated parts You can, if you want to, work with parts of your ...


10

Yves Papegay has developed SymbolicC in order to automate the conversion of his models to C. This is used by Airbus. For more information see his presentations in the Wolfram Library Archive http://library.wolfram.com/infocenter/search/?search_results=1&search_person_id=6281 especially this one http://library.wolfram.com/infocenter/Conferences/7477/ ...


10

OK, FrontEnd: After creating the "overview" button below just click first on your function definition and then on the button and under the function definition you will get (nearly) what you want, i.e. : Part 1. Step 1. Local variables Part 1. Step 2. Option variables Part 2. Step 1. Check for null Input Part 2. Step 2.:1 Check for groups Part 2. ...


9

I would suggest something more simple-minded than Rolf's sophisticated implementation: Clear[extractComments]; extractComments[boxes_] := StringJoin@ Riffle[ Cases[boxes, r : RowBox[{"(*", ___, "*)"}] :> StringJoin@Cases[r, _String, Infinity], Infinity], "\n"]; and the palette: CreatePalette[ ...


8

I'm very sure you will find answers to all your questions in very detailed form on this site, since the issues you have were already discussed. Please start reading Metaprogramming in Mathematica Replace inside held expressions In general, you should look for answers from Leonid, since he did a great deal of work documenting many meta-programming ...


8

Since OP mentions Lisp quasiquote mechanism, maybe we can implement something similar in Mathematica. Disclaimer: I've never written a line of code in any of Lisp dialects. In Mathematica rules for evaluation of an expression are "attached" to symbols in this expression through various ...Values and Attributes (evaluation of many built-in symbols is ...


7

I feel slightly foolish for posting this, because I figured it our almost immediately after posting my question, but the answer is to follow C's philosophy that type declaration should mimic use. CFunction is used only for function declaration and definition; for function types, you use CCall: CTypedef["double", CCall[CDereference[rhs], {"double", ...


7

Unfortunately, it does not appear that this is possible without the Enterprise edition of Mathematica (or, perhaps, an alternative conclusion is that Mathematica is not the best tool for this job). As Mr. Wizard points out: I'm afraid you are in for disappointment. Apart from the Enterprise Edition or Wolfram Player Pro Mathematica does not have this ...


7

This is a very very specific example. There's something I wanted to do for a while but I didn't have time yet. Exporting 3D graphics into PDF produces lots and lots and lots of triangles (for the gradients), which aren't joined properly. The result is that rendering time in a PDF reader is very long, the PDF size is very large, and the whole result just ...


6

A possibly more general function to be aware of is Tuples: FromDigits /@ Tuples[{0, 1, 2}, 4] {0, 1, 2, 10, 11, 12, 20, 21, 22, 100, 101, 102, 110, 111, 112, 120, 121, 122, 200, 201, 202, 210, 211, 212, 220, 221, 222, 1000, 1001, 1002, 1010, 1011, 1012, 1020, 1021, 1022, 1100, 1101, 1102, 1110, 1111, 1112, 1120, 1121, 1122, 1200, 1201, 1202, ...


5

To achieve this, we can define a new SymbolicC construct that won't get semicolons at the end. Let's call it CInlineCode. We will need to provide translation rules for conversions to a string. This is done in terms of SymbolicC`GenerateCode (which is a slightly lower level version to ToCCodeString). In general, translation rules are attached to ...


5

The example I'm familiar with is the claim that some of the formulae used internally by Mathematica's functions were derived using Mathematica itself. From here: For machine precision most special functions use Wolfram Language-derived rational minimax approximations. From here: Most of the algorithms in the Wolfram Language, including all their ...


4

I think you'll find this faster than either of the above: f=FromDigits@Transpose@IntegerDigits[Range[0, #], 3, IntegerLength[#, 3]] &; Use e.g.: f@12345 is equalvlent to FromDigits /@ IntegerDigits[Range[0, 12345], 3] above. Even faster: FromDigits@Transpose@PadLeft@Tuples[{0, 1, 2}, 11];


4

This isn't a complete answer, just something to get you started. I think it would useful to think of a function, say countOpenGates, which would look something like this: countOpenGates[mat : {{(0 | 1) ..} ..}] /; MatrixQ[mat] := Total[Times @@@ mat] If "open" means "all subunits are open", i.e. have value 1, then their product is 1. And if any ...


3

Here is a more complete example. Needs["SymbolicC`"] ClearAll[fun, $opsPatt]; $opsPatt = Alternatives @@ {Minus, PreDecrement, Decrement, PreIncrement, Increment, Greater, Less, GreaterEqual, LessEqual, Equal, Unequal, Mod, Divide, Times, Subtract, Plus, BitShiftLeft, BitShiftRight, BitAnd, BitXor, BitOr, And, Or, Not}; ...


3

Use option ClippingStyle->Automatic data = Table[ 1/Sqrt[x^2 + y^2] + Cos[x*y] - 1/Sqrt[(x - 0.5)^2 + (y - 0.5)^2], {x, -3.01, 3, 0.1}, {y, -3.01, 3, 0.1}]; ListContourPlot[data, ContourLabels -> Automatic, Contours -> 20, ColorFunction -> "BlueGreenYellow", ClippingStyle -> Automatic, PlotLegends -> Automatic]


3

This can be a start: ClearAll[fun, $opsPatt]; $opsPatt = Alternatives @@ {Less, Greater, LessEqual, GreaterEqual, Equal, Unequal}; SetAttributes[fun, HoldAll]; fun[code_] := ReleaseHold[ Hold[code] //. { (head : $opsPatt)[x_, y_] :> COperator[head, {x, y}], HoldPattern[Set[lhs_, rhs_]] :> CAssign[lhs, rhs], ...


3

Further possibilities that I can think of might be Genetic Programming. Code obfuscation Individualization of source code in order to track piracy.


3

Actually Leonid didn't use SymbolicC in his answer yesterday, he mentioned it as another more powerful way to potentially deal with my question. I would assume that at some stage of Compile[...,CompilationTarget->"C"] that Mathematica builds an internal expression using SymbolicC. It would be nice to be able to "intercept" it at this stage. To solve my ...


3

As it turns out, the answer is $InstallationDirectory/SystemFiles/IncludeFiles/C/. Thanks Heike!


2

My first answer explains that Mathematica's replacement rules perform destructuring. This answer is intended to complement jVincent's method, which I see is appreciated. My aim is to provide Attributes for the pattern-based function. This requires that the head evaluate therefore SubValues may not be used. Here are two separate approaches. Module A ...


2

You can use Subtract or Differences to get the differences in the index and use FreeQ to test if every element is True. This removes the need for the ugly #2[[1]]-#2[[2]] and also the Flatten and And@@ at the end. triDiagonalQ[mat_?MatrixQ] :=FreeQ[MapIndexed[(#1 == 0 || Abs[Subtract @@ #2] <= 1) &, mat, {2}], False] The pattern test ...


2

Yes, it's possible. Use ToCCodeString[..., "Indent" -> 1] I found this by checking Options[ToCCodeString]. The "Indent" option appears to control the number of tabs that will be used for indenting.



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