Tag Info

Hot answers tagged

46

Update: Mathematica 10 has introduced Association, which can be used as a close equivalent of structs. params = <| "par1" -> 1, "par2" -> 2 |> params["par1"] (* ==> 1 *) In version 10 pure functions can have named arguments, and can be effectively used as expression templates where the slots can be populated from an association. This is ...


43

This answer may be unacceptable right from the outset because it uses undocumented functions. However, it has advantages over some of the approaches suggested so far which might be redeeming enough in certain scenarios to recommend it in practice. In particular, it provides totally encapsulated state (unlike, e.g., DownValues or Temporary symbols) and O(1) ...


31

There were several attempts to emulate structs in Mathematica. Emphasis on emulate, since AFAIK there is no built - in support for it yet. One reason for that may be that structs are inherently mutable, while idiomatic Mathematica gravitates towards immutability. You may find these discussions interesting: Struct-data-type-in-mathematica ...


29

Using symbols to store data and object-like functions Here are interesting functions to use symbols like objects. (I originally posted these thoughts in What is in your Mathematica tool bag?). The post has grown quite big over time as I used it to record ideas. It's divided into three parts, one describing the function Keys, another one where properties ...


24

In practice, enforcing strong types in Mathematica seldom pays off, just because, as mentioned by @belisarius, Mathematica is untyped (and perhaps more so than most other langauges, since it is really a term-rewriting system). So, most of the time, the suggestion of @Mr.Wizard describes what I'd also do. The way to define ADT-s (strong types) was described ...


20

The answers already posted show that built-in Mathematica functionality can be used to get the meaningful functionality provided by a C struct. If you want your code to be readable by other Mathematica users, I suggest using a list of rules as already advised above. However, if you really want struct-style syntax I'll offer an implementation that I've ...


17

As you mentioned in your question and belisarius illustrates above, you can check arguments with arbitrary pattern matching. When I need to do checks of this kind I often use a couple of methods; I will define the pattern once and then reference it by name: p1 = {{_Integer, {_Integer ...}} ...}; dat = {{100, {1, 2, 3, 4, 5}}, {105, {2, 4, 6, 8}}, {42, ...


16

So the naive way to set up a data structure like struct is, as the OP suggested, to simply used DownValues and/or SubValues. In the below, I use SubValues. Copying the Wikipedia C language struct example struct account { int account_number; char *first_name; char *last_name; float balance; }; struct account s; // Create new account labelled s ...


15

As the responses show, there are a number of quick "probably real" tests. In general, the problem is undecidable, however. This is an easy corollary of Richardson's theorem, which says that it is impossible to decide if two real expressions $x$ and $y$ are equal. Assuming Richardson's theorem, note that $(x-y)i$ is real if and only if $x=y$. As a more ...


15

No ADT in Mma (natively at least) ... but in your case you could use pattern matching: yours = {{100, {1, 2, 3, 4, 5}}, {105, {2, 4, 6, 8}}, {42, {42, 39, 56}}}; f[x_] := 1 /; MatchQ[x, List[List[_Integer, List[_Integer ...]] ...]] f[yours] f["mySymbol"] (*-> 1 f["mySymbol"] *)


15

I arrived very late to this party and I'm very much afraid that nobody comes here anymore. Still I'm posting this in hope that an occasional visitor may find it a practical approach to implementing data structures with named fields within Mathematica. The concept The idea is to use protected symbols to name a structure and its fields. The symbol that names ...


15

Update: Internal`RealValuedNumericQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, True, True, False, False} *) or Internal`RealValuedNumberQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, False, True, False, False} *) Using @RM's test list listRM = With[{n = 10^5}, ...


13

You can effectively create your own types by using the feature that Mathematica expressions have a Head, the head can be used to define a type. Functions can then use the Head value to apply only to arguments matching the defined type. A version with loose format checking, format checked only upon creation,can be implemented as simply as this: (* Define ...


11

I think a solution based on pattern matching will be much faster than using Element (which is more mathematical in nature) or only pattern tests or anything else that forces evaluation, since we can bypass the main evaluator. However, it is not possible to completely escape evaluation, because there can be infinitely large number of possibilities for a real ...


9

RealQ[x_] := Element[x, Reals] === True It fulfills all your samples and I think is generally correct.


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

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


6

You can use ImageDimensions for this purpose (in this case for a multi-frame DICOM): imagestack = Import["http://www.barre.nom.fr/medical/samples/files/MR-MONO2-8-\16x-heart.gz"]; Length[imagestack] ImageDimensions /@ imagestack (* 16 *) (* {{256, 256}, {256, 256}, {256, 256}, {256, 256}, {256, 256}, {256, 256}, {256, 256}, {256, 256}, {256, ...


6

A few examples fun[x_] := x^2 sphere = Graphics3D[{Sphere[{0, 0, 0}, 0.01]}, Boxed -> False, ImageSize -> 30]; str = {"1", "Pi", "{f}", "f", "f[x]", "f+f", "Inactivate[f+f,Plus]", "Hold[1+2+3]", "{1,{2,{3}}}", "fun[2]", "fun[x]", "Cos[Exp[x]]", "Red", "sphere", "DateObject[{2014,10}]"}; table = With[{exp = ToExpression /@ str}, ...


5

One can get information about the images in a file from the metadata, provided it is there in the first place. For example, in Yves Klett's example file, the "MetaInformation" contains information about "FrameCount", "Rows", and "Columns". These can be obtained as follows: {"FrameCount", "Rows", "Columns"} /. ...


5

The argument pattern can be read directly from the CompiledFunction expression as DaveStrider commented: cf = Compile[{{x, _Real}, {y, _Integer}}, Round[x/y]]; cf[[2]] {_Real, _Integer} The result information is printed by the CompiledFunctionTools package command CompilePrint: Needs["CompiledFunctionTools`"] CompilePrint[cf] 2 arguments ...


5

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


5

I wasn't planning to add an answer, but this now seems like it has its place in this fine list of answers: realQ[x_?NumericQ] := Head[x] =!= Complex realQ[_] := False While maybe not the absolute fastest, it is fast and also relatively simple and uses only System` functions.


4

You could use UpValues: mylist = {"Alice", "Bob", "Carol"}; numlist = {1, 2, 5, 3}; SetAttributes[NETType, HoldAll] NETType[mylist] ^:= String NETType[numlist] ^:= Integer {NETType[mylist], NETType[numlist]} (* Returns: {String, Integer} *) Of course, this does not perform any checks that the elements in the list actually are of the type claimed.


4

This is a simple approach that requires you to include the assumptions about all the identified variables in the second argument (I assume that's what you want to do): returnsComplex[string_, assumptions_] := TrueQ[ Simplify[(ToExpression[string]) \[Element] Complexes, assumptions]] returnsComplex["1/x+7x^2+Sin[x]", x \[Element] Complexes] (* ==> ...


3

Just to illustrate Szabolcs's comments, see the behaviour of: Element[1., Rationals] This returns the input. versus Element[Rationalize[1.],Rationals] This returns True (as expected) and Element[Rationalize[1.2],Rationals] This returns True.


3

I figured it out, I need to use Item indexer, but item index starts from 0, not 1: If you write a class in C# and give it an indexer, the compiler creates a public property named Item for you. This is a parameterized property, meaning that it takes an argument like a method call. The indexer syntax is just a shorthand for calling the Item property. See ...


2

It sounds like all you are looking for is a generic storage using MySQL. Then your translation of _String to TEXT makes sense, but I would consider _Real as a DOUBLE column, depending on your precision requirements. Additionally, I would probably separate the inner list: {_String, {_String, _Real}, _Real} into: {_String, _String, _Real, _Real} So ...


2

Many functions in Mathematica don't care about the head actually being List so you can do something like this: In[516]:= s = StringList["1", "foo", "bar"] Out[516]= StringList["1", "foo", "bar"] In[518]:= Length[s] Out[518]= 3 In[519]:= Prepend[s, "z"] Out[519]= StringList["z", "1", "foo", "bar"] In[523]:= Map[StringLength, s] Out[523]= StringList[1, ...


1

In case you need to store real numbers exactly as Mathematica has calculated them you can store them as a string. This may be required if you retrieve numbers off your database for comparison - the database will probably reduce the precision resulting in mismatches. To store a real as a string you can make use of InputForm. However, exponential forms have ...



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