Tag Info

Hot answers tagged

42

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


40

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


29

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


28

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


23

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


19

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


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


16

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


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

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


14

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


14

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


12

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.


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


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

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.


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


1

I do not know if there is a trick to do that using Attributes and such. But just wanted to suggest a simple method, may be it work for you, may be not. Mathematica lists are very flexible, they can be ragged in shape. Hence you could always have the first entry in your lists be the 'type' of the list content, by having the head of the types of the item in ...



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