Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #11817

Re: set option flag in function definition

From Murray Eisenberg <murray@math.umass.edu>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: set option flag in function definition
Date 2012-09-19 08:58 +0000
Message-ID <k3c1fl$f0k$1@smc.vnet.net> (permalink)
References <20120918074139.41A2D6853@smc.vnet.net>
Organization Time-Warner Telecom

Show all headers | View raw


On Sep 18, 2012, at 3:41 AM, Joug Raw <jougraw@gmail.com> wrote:

> ...I want to have a function that executes certain operation when I chose the
> corresponding option flag.
>
> For example,
>
> a function called "f"
>
> when I call it like f[arg1,arg2,arg3, optionX]
> it executes command
> arg1/arg2+arg3
>
> If I call it like f[arg1,arg2,arg3,optionY]
> it executes command
> arg1*arg2-arg3
>
> If I call it like f[arg1,arg2,arg3,optionSomethingElse]
> it returns me
> "No appropriate option flag was found. Please indicate correct options"
>
> ...I am wondering if I can do
> the same in Mathematica easily?


Yes, it can be done very easily in Mathematica:

  f[a_, b_, c_, method -> "one"] := a/b+c
  f[a_, b_, c_, method -> "two"] := a b-c
  f[a_, b_, c_, method -> _] := "No relevant value for 'method' found"
  f[a_, b_, c_, opt_ -> _] := "I don't understand this option"

(I shortened argument names; the option name "method" I used is quite arbitrary.)

The key to the above is that Mathematica always uses a more specific rule before it uses a more general one.

If, though, you want a single expression for defining the function f, then yes that's also possible but more complicated; you cold use, e.g., FilterRules.

---
Murray Eisenberg                                     
murray@math.umass.edu
Mathematics & Statistics Dept.      
Lederle Graduate Research Tower      phone 413 549-1020 (H)
University of Massachusetts                  413 545-2859 (W)
710 North Pleasant Street                      fax   413 545-1801
Amherst, MA 01003-9305





Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: set option flag in function definition Murray Eisenberg <murray@math.umass.edu> - 2012-09-19 08:58 +0000

csiph-web