Re: Options[] creation
- To: mathgroup at smc.vnet.net
- Subject: [mg39235] Re: Options[] creation
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Wed, 5 Feb 2003 00:11:03 -0500 (EST)
- References: <b1nq2h$o3o$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Kyriakos,
Here is are two ways (but adding message can often take longer than the
original programming - much depends how much you want to do). In general
we want to model built in function behaviour by returning univaluated when
something goes wrong.
(1)
Options[f]:=
{Diameter->1,Shape-> Circle};
f[x_, opts___?OptionQ]:=
Module[{shp, diam},
{shp,diam}= {Shape,Diameter}/.
Flatten[{opts}]/.Options[f];
If[
MatchQ[{shp,diam},
{Circle,_?Positive}|{Ellipsis,{_?Positive,_?Positive}}],
program[x,opts],
Message[f::bdshpdiam]
]]
Define the message.
f::bdshpdiam= "The values of the options Shape and Diameter
incompatible.";
TEST.
f[aa]
program[aa]
f[aa, Diameter->{2,3}]
f::bdshpdiam: The values of the options Shape and Diameter
incompatible.
(2)
Here is an example of a flexible trechnique that allows us to monitor the
evaluation process and act on what happens.
middle[x___]:=With[{result=middle1[x]},result/;result=!=$Failed]
We now test all aspects of the input and on-going evaluation and act on what
we find.
middle1[x___]:=
Module[{tag},
Catch[If[
Length[{x}]===1,
If[OddQ[Length[x]],Throw[x[[Ceiling[Length[x]/2]]],tag],
Message[middle::nodd];Throw[$Failed, tag]],
Message[middle::argx,middle, Length[{x}]];Throw[$Failed,tag]
],
tag]
]
middle::nodd =
"The argument of middle is expected to be normal with an odd number
of elements";
TEST
middle[{1,2}]
middle::nodd: The argument of middle is expected to be normal with
an odd \
number of elements
middle[{1,2}]
middle[1,2]
middle::argx: middle called with 2 arguments; 1 argument is
expected.
middle[1,2]
middle[p[1,2,3]]
2
--
Allan
---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565
"Kyriakos Chourdakis" <k.chourdakis at qmul.ac.uk> wrote in message
news:b1nq2h$o3o$1 at smc.vnet.net...
> Dear all,
>
> Suppose I create a function f[x_,opts___]
> with options
> Shape in {Circle, Ellipsis} and Diameter in R+, DiameterLong in R+,
> DiameterShort in R+
> Say that the defaults are
> Options[x]={Shape->Circle, Diameter->1.}
>
> The option Diameter makes sence only when Shape->Circle, and
> The options DiameterShort/Long make sense only when Shape->Ellipsis
>
> Is there a quick way to tell Mathematica to warn if these conditions are
> not satisfied? I could write a series of boolean tests, but I was
wondering
> if there is a more elegant way.
>
> Best,
>
> Kyriakos
>
>
>
> _____+*"*+____+*"*+___+*"*+__+*"*+_
>
> Kyriakos Chourdakis
> Lecturer in Financial Economics
>
> URL: http://www.qmw.ac.uk/~te9001
> tel: (++44) (+20) 7882 5086
> Dept of Economics
> University of London, QM
> London E1 4NS
> U.K.
>