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


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

Re: set option flag in function definition

Started byMurray Eisenberg <murray@math.umass.edu>
First post2012-09-19 08:58 +0000
Last post2012-09-19 08:58 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.soft-sys.math.mathematica

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#11817 — Re: set option flag in function definition

FromMurray Eisenberg <murray@math.umass.edu>
Date2012-09-19 08:58 +0000
SubjectRe: set option flag in function definition
Message-ID<k3c1fl$f0k$1@smc.vnet.net>
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





[toc] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web