MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Assertions in Mathematica?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113458] Re: Assertions in Mathematica?
  • From: Albert Retey <awnl at gmx-topmail.de>
  • Date: Fri, 29 Oct 2010 06:29:47 -0400 (EDT)
  • References: <iabc4e$5hg$1@smc.vnet.net>

Hi,


> Naively, I tried defining:
> 
> Assert[exp_, msg__] := If[!exp, Message[msg]; Abort[]]
> 
> ....which, of course, failed to work (as I've learned to expect);
> instead it produced a cryptic error "Message::name : Message name
> .... is not of the form symbol::name or symbol::name::language."


> But hope springs eternal!  If someone is kind enough to tell me
> how I could implement my Assert, I'd be most grateful.  

I guess this would be doing what you intended:

SetAttributes[assert, HoldAll]

assert[exp_, msg__] := If[! exp, Message[msg]; Abort[]]

test::error = "value is negative!"
x = -1;
assert[x > 0, test::error]

> If someone
> can tell me how I could have arrived at this answer by myself by
> consulting the documentation, I'd be ecstatic.

my impression is that all you were missing was the HoldAll attribute for
the assert function. My personal experience is that frustration with the
documentation and the behaviour of Mathematica has reduced a lot for me
at the point when I started to understand the details of how the
evaluation process works. It is one of the subtleties that many users
try to avoid to learn since it seems to not be crucial to their tasks at
hand. On the other hand, it is the one clue to most of the mathematica
oddities so I think even if you are an on and off user, you would gain a
lot from understanding it. The tutorials listed in the
guide/EvaluationControl documentation page seem to be a good starting
point, actually I think they contain all the information needed.

I found many of the tutorials in the documentation be a valuable source
of information, so if I am not looking for the details of a known
function I usually look for tutorials. In version 7 the virtual book
gives an overview of the existing tutorials, you can find even some more
relevant tutorials there in the section Core Language -> Evaluation of
Expressions.

hth,

albert


  • Prev by Date: Re: How to make Mathematica automatically save a notebook to the
  • Next by Date: Re: Importing data
  • Previous by thread: Assertions in Mathematica?
  • Next by thread: Re: Assertions in Mathematica?