What is an example of of idiomatic “typed” WolframScript?What are the best practices / most common / idiomatic ways to report errors in Mathematica?Difference between “wolframscript -f” and “wolframscript -script”Wolframscript running slow on linux?Line by line processing with a WolframScriptHow to define “typed” objects and their operator specializations?A question on wolframscriptWolframscript output not evaluatedPassing arguments into a script in WolframScriptWolframscript does not terminateQuerying WolframAlpha from WolframScriptRunning CloudDeploy from WolframScript

Find the radius of the hoop.

Are the requirements of a Horn of Valhalla cumulative?

How do we separate rules of logic from non-logical constraints?

13th chords on guitar

What exactly did Ant-Man see that made him say that their plan worked?

How to securely dispose of a smartphone?

Why did NASA wet the road in front of the Space Shuttle crawler?

Is Cyclic Ether oxidised by periodic acid

Different budgets within roommate group

If two black hole event horizons overlap (touch) can they ever separate again?

How to describe POV characters?

I just started should I accept a farewell lunch for a coworker I don't know?

How to unit test methods which using static methods?

Do the 26 richest billionaires own as much wealth as the poorest 3.8 billion people?

Just graduated with a master’s degree, but I internalised nothing

Reusable spacecraft: why still have fairings detach, instead of open/close?

Can European countries bypass the EU and make their own individual trade deal with the U.S.?

Security Patch SUPEE-11155 - Possible issues?

What do you call a notepad used to keep a record?

Adjective for 'made of pus' or 'corrupted by pus' or something of something of pus

SRAM Twist Shifter Paired with Shimano Rear Derailleur

How did researchers find articles before the Internet and the computer era?

Using the ArcGIS 'select by location' tool in ModelBuilder?

Losing queen and then winning the game



What is an example of of idiomatic “typed” WolframScript?


What are the best practices / most common / idiomatic ways to report errors in Mathematica?Difference between “wolframscript -f” and “wolframscript -script”Wolframscript running slow on linux?Line by line processing with a WolframScriptHow to define “typed” objects and their operator specializations?A question on wolframscriptWolframscript output not evaluatedPassing arguments into a script in WolframScriptWolframscript does not terminateQuerying WolframAlpha from WolframScriptRunning CloudDeploy from WolframScript






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


I'd like to make my own "typed function" in WolframScript. Suppose the type we desire is called money, and we'd like to make a function called doubleOurMoney which doubles any money argument but throws an error on everything else. How do we do this?



Attempt: This isn't quite right but perhaps is a good starting point:



doubleOurMoney[money[x_Real]] := money[2 x]
doubleOurMoney[money[2.0]] (* Should return money[4.], and does. *)

doubleOurMoney[money["nonsense"]] (* How do we make this throw an error? *)
doubleOurMoney[2] (* How do we make this throw an error? *)
doubleOurMoney["nonsense"] (* How do we make this throw an error? *)
doubleOurMoney[symbol] (* How do we make this throw an error? *)


Questions:



  1. How do we throw "type errors" in this context?

  2. Right now money accepts real numbers as arguments; how could we make it take any "number" as an argument (Integer, etc) but throw an error on everything else?

  3. Is my attempt at "typed WolframScript" an idiomatic approach to type-checking in Wolfram? If not, what is the idiomatic approach here to check that inputs to a function are sensible?









share|improve this question











$endgroup$











  • $begingroup$
    There is probably a duplicate for this question, but I don't see it offhand.
    $endgroup$
    – Jason B.
    8 hours ago






  • 1




    $begingroup$
    related: What are the best practices / most common / idiomatic ways to report errors in Mathematica?
    $endgroup$
    – WReach
    7 hours ago

















4












$begingroup$


I'd like to make my own "typed function" in WolframScript. Suppose the type we desire is called money, and we'd like to make a function called doubleOurMoney which doubles any money argument but throws an error on everything else. How do we do this?



Attempt: This isn't quite right but perhaps is a good starting point:



doubleOurMoney[money[x_Real]] := money[2 x]
doubleOurMoney[money[2.0]] (* Should return money[4.], and does. *)

doubleOurMoney[money["nonsense"]] (* How do we make this throw an error? *)
doubleOurMoney[2] (* How do we make this throw an error? *)
doubleOurMoney["nonsense"] (* How do we make this throw an error? *)
doubleOurMoney[symbol] (* How do we make this throw an error? *)


Questions:



  1. How do we throw "type errors" in this context?

  2. Right now money accepts real numbers as arguments; how could we make it take any "number" as an argument (Integer, etc) but throw an error on everything else?

  3. Is my attempt at "typed WolframScript" an idiomatic approach to type-checking in Wolfram? If not, what is the idiomatic approach here to check that inputs to a function are sensible?









share|improve this question











$endgroup$











  • $begingroup$
    There is probably a duplicate for this question, but I don't see it offhand.
    $endgroup$
    – Jason B.
    8 hours ago






  • 1




    $begingroup$
    related: What are the best practices / most common / idiomatic ways to report errors in Mathematica?
    $endgroup$
    – WReach
    7 hours ago













4












4








4


2



$begingroup$


I'd like to make my own "typed function" in WolframScript. Suppose the type we desire is called money, and we'd like to make a function called doubleOurMoney which doubles any money argument but throws an error on everything else. How do we do this?



Attempt: This isn't quite right but perhaps is a good starting point:



doubleOurMoney[money[x_Real]] := money[2 x]
doubleOurMoney[money[2.0]] (* Should return money[4.], and does. *)

doubleOurMoney[money["nonsense"]] (* How do we make this throw an error? *)
doubleOurMoney[2] (* How do we make this throw an error? *)
doubleOurMoney["nonsense"] (* How do we make this throw an error? *)
doubleOurMoney[symbol] (* How do we make this throw an error? *)


Questions:



  1. How do we throw "type errors" in this context?

  2. Right now money accepts real numbers as arguments; how could we make it take any "number" as an argument (Integer, etc) but throw an error on everything else?

  3. Is my attempt at "typed WolframScript" an idiomatic approach to type-checking in Wolfram? If not, what is the idiomatic approach here to check that inputs to a function are sensible?









share|improve this question











$endgroup$




I'd like to make my own "typed function" in WolframScript. Suppose the type we desire is called money, and we'd like to make a function called doubleOurMoney which doubles any money argument but throws an error on everything else. How do we do this?



Attempt: This isn't quite right but perhaps is a good starting point:



doubleOurMoney[money[x_Real]] := money[2 x]
doubleOurMoney[money[2.0]] (* Should return money[4.], and does. *)

doubleOurMoney[money["nonsense"]] (* How do we make this throw an error? *)
doubleOurMoney[2] (* How do we make this throw an error? *)
doubleOurMoney["nonsense"] (* How do we make this throw an error? *)
doubleOurMoney[symbol] (* How do we make this throw an error? *)


Questions:



  1. How do we throw "type errors" in this context?

  2. Right now money accepts real numbers as arguments; how could we make it take any "number" as an argument (Integer, etc) but throw an error on everything else?

  3. Is my attempt at "typed WolframScript" an idiomatic approach to type-checking in Wolfram? If not, what is the idiomatic approach here to check that inputs to a function are sensible?






scripting data-types






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 6 hours ago









user64494

4,1252 gold badges14 silver badges23 bronze badges




4,1252 gold badges14 silver badges23 bronze badges










asked 8 hours ago









GeorgeGeorge

3021 silver badge8 bronze badges




3021 silver badge8 bronze badges











  • $begingroup$
    There is probably a duplicate for this question, but I don't see it offhand.
    $endgroup$
    – Jason B.
    8 hours ago






  • 1




    $begingroup$
    related: What are the best practices / most common / idiomatic ways to report errors in Mathematica?
    $endgroup$
    – WReach
    7 hours ago
















  • $begingroup$
    There is probably a duplicate for this question, but I don't see it offhand.
    $endgroup$
    – Jason B.
    8 hours ago






  • 1




    $begingroup$
    related: What are the best practices / most common / idiomatic ways to report errors in Mathematica?
    $endgroup$
    – WReach
    7 hours ago















$begingroup$
There is probably a duplicate for this question, but I don't see it offhand.
$endgroup$
– Jason B.
8 hours ago




$begingroup$
There is probably a duplicate for this question, but I don't see it offhand.
$endgroup$
– Jason B.
8 hours ago




1




1




$begingroup$
related: What are the best practices / most common / idiomatic ways to report errors in Mathematica?
$endgroup$
– WReach
7 hours ago




$begingroup$
related: What are the best practices / most common / idiomatic ways to report errors in Mathematica?
$endgroup$
– WReach
7 hours ago










1 Answer
1






active

oldest

votes


















6












$begingroup$

Here is an idiom used by many built-in functions to achieve this effect:



doubleOurMoney::badarg = "`1` should be of the form money[number]";
doubleOurMoney[money[x_?NumericQ]] := money[2 x];
doubleOurMoney[args___] := (
Message[doubleOurMoney::badarg, args];
Null /; False
)


Here I'm using _?NumericQ instead of _Real to make your function work on all numeric input. That first definition will only fire for numeric inputs of the right form, but the second definition will work for any input. The second definition will issue a message telling the user what type of input is needed:



doubleOurMoney[money[2]]
(* money[4] *)

doubleOurMoney[3]

During evaluation of doubleOurMoney::badarg: 3 should be of the form money[number]
(* doubleOurMoney[3] *)

doubleOurMoney["bob"]

During evaluation of doubleOurMoney::badarg: bob should be of the form money[number]
(* doubleOurMoney["bob"] *)


That last bit of trickery is so that your function, after issuing a message, returns unevaluated. You could replace the Null /; False with $Failed just as easily.






share|improve this answer









$endgroup$












  • $begingroup$
    This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
    $endgroup$
    – George
    7 hours ago










  • $begingroup$
    That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
    $endgroup$
    – Jason B.
    7 hours ago










  • $begingroup$
    @JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
    $endgroup$
    – b3m2a1
    5 hours ago













Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "387"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f201041%2fwhat-is-an-example-of-of-idiomatic-typed-wolframscript%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









6












$begingroup$

Here is an idiom used by many built-in functions to achieve this effect:



doubleOurMoney::badarg = "`1` should be of the form money[number]";
doubleOurMoney[money[x_?NumericQ]] := money[2 x];
doubleOurMoney[args___] := (
Message[doubleOurMoney::badarg, args];
Null /; False
)


Here I'm using _?NumericQ instead of _Real to make your function work on all numeric input. That first definition will only fire for numeric inputs of the right form, but the second definition will work for any input. The second definition will issue a message telling the user what type of input is needed:



doubleOurMoney[money[2]]
(* money[4] *)

doubleOurMoney[3]

During evaluation of doubleOurMoney::badarg: 3 should be of the form money[number]
(* doubleOurMoney[3] *)

doubleOurMoney["bob"]

During evaluation of doubleOurMoney::badarg: bob should be of the form money[number]
(* doubleOurMoney["bob"] *)


That last bit of trickery is so that your function, after issuing a message, returns unevaluated. You could replace the Null /; False with $Failed just as easily.






share|improve this answer









$endgroup$












  • $begingroup$
    This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
    $endgroup$
    – George
    7 hours ago










  • $begingroup$
    That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
    $endgroup$
    – Jason B.
    7 hours ago










  • $begingroup$
    @JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
    $endgroup$
    – b3m2a1
    5 hours ago















6












$begingroup$

Here is an idiom used by many built-in functions to achieve this effect:



doubleOurMoney::badarg = "`1` should be of the form money[number]";
doubleOurMoney[money[x_?NumericQ]] := money[2 x];
doubleOurMoney[args___] := (
Message[doubleOurMoney::badarg, args];
Null /; False
)


Here I'm using _?NumericQ instead of _Real to make your function work on all numeric input. That first definition will only fire for numeric inputs of the right form, but the second definition will work for any input. The second definition will issue a message telling the user what type of input is needed:



doubleOurMoney[money[2]]
(* money[4] *)

doubleOurMoney[3]

During evaluation of doubleOurMoney::badarg: 3 should be of the form money[number]
(* doubleOurMoney[3] *)

doubleOurMoney["bob"]

During evaluation of doubleOurMoney::badarg: bob should be of the form money[number]
(* doubleOurMoney["bob"] *)


That last bit of trickery is so that your function, after issuing a message, returns unevaluated. You could replace the Null /; False with $Failed just as easily.






share|improve this answer









$endgroup$












  • $begingroup$
    This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
    $endgroup$
    – George
    7 hours ago










  • $begingroup$
    That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
    $endgroup$
    – Jason B.
    7 hours ago










  • $begingroup$
    @JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
    $endgroup$
    – b3m2a1
    5 hours ago













6












6








6





$begingroup$

Here is an idiom used by many built-in functions to achieve this effect:



doubleOurMoney::badarg = "`1` should be of the form money[number]";
doubleOurMoney[money[x_?NumericQ]] := money[2 x];
doubleOurMoney[args___] := (
Message[doubleOurMoney::badarg, args];
Null /; False
)


Here I'm using _?NumericQ instead of _Real to make your function work on all numeric input. That first definition will only fire for numeric inputs of the right form, but the second definition will work for any input. The second definition will issue a message telling the user what type of input is needed:



doubleOurMoney[money[2]]
(* money[4] *)

doubleOurMoney[3]

During evaluation of doubleOurMoney::badarg: 3 should be of the form money[number]
(* doubleOurMoney[3] *)

doubleOurMoney["bob"]

During evaluation of doubleOurMoney::badarg: bob should be of the form money[number]
(* doubleOurMoney["bob"] *)


That last bit of trickery is so that your function, after issuing a message, returns unevaluated. You could replace the Null /; False with $Failed just as easily.






share|improve this answer









$endgroup$



Here is an idiom used by many built-in functions to achieve this effect:



doubleOurMoney::badarg = "`1` should be of the form money[number]";
doubleOurMoney[money[x_?NumericQ]] := money[2 x];
doubleOurMoney[args___] := (
Message[doubleOurMoney::badarg, args];
Null /; False
)


Here I'm using _?NumericQ instead of _Real to make your function work on all numeric input. That first definition will only fire for numeric inputs of the right form, but the second definition will work for any input. The second definition will issue a message telling the user what type of input is needed:



doubleOurMoney[money[2]]
(* money[4] *)

doubleOurMoney[3]

During evaluation of doubleOurMoney::badarg: 3 should be of the form money[number]
(* doubleOurMoney[3] *)

doubleOurMoney["bob"]

During evaluation of doubleOurMoney::badarg: bob should be of the form money[number]
(* doubleOurMoney["bob"] *)


That last bit of trickery is so that your function, after issuing a message, returns unevaluated. You could replace the Null /; False with $Failed just as easily.







share|improve this answer












share|improve this answer



share|improve this answer










answered 8 hours ago









Jason B.Jason B.

50k3 gold badges93 silver badges199 bronze badges




50k3 gold badges93 silver badges199 bronze badges











  • $begingroup$
    This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
    $endgroup$
    – George
    7 hours ago










  • $begingroup$
    That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
    $endgroup$
    – Jason B.
    7 hours ago










  • $begingroup$
    @JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
    $endgroup$
    – b3m2a1
    5 hours ago
















  • $begingroup$
    This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
    $endgroup$
    – George
    7 hours ago










  • $begingroup$
    That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
    $endgroup$
    – Jason B.
    7 hours ago










  • $begingroup$
    @JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
    $endgroup$
    – b3m2a1
    5 hours ago















$begingroup$
This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
$endgroup$
– George
7 hours ago




$begingroup$
This is great. Is there a way to declare separately (at the beginning) that money only takes form money[x_?NumericQ] and for all other money[args___] we throw an error? And then that way we don't have to do it within doubleOurMoney but can just say doubleOurMoney takes a money[..] (however it is defined).
$endgroup$
– George
7 hours ago












$begingroup$
That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
$endgroup$
– Jason B.
7 hours ago




$begingroup$
That is a bit different - you could make a definition for money, like money[ arg: Except[_?NumericQ] ] := (Message[ money::badarg];$Failed). In that case, money would return $Failed for any non-numeric input.
$endgroup$
– Jason B.
7 hours ago












$begingroup$
@JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
$endgroup$
– b3m2a1
5 hours ago




$begingroup$
@JasonB. or even better use SetValid on valid data (and only run the check on stuff without the bit) and then doubleOurMoney need only check for the valid bit.
$endgroup$
– b3m2a1
5 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Mathematica Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f201041%2fwhat-is-an-example-of-of-idiomatic-typed-wolframscript%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

In Tikz, how to set a node's label alignment to the left?Rotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?Numerical conditional within tikz keys?TikZ/ERD: node (=Entity) label on the insideLine up nested tikz enviroments or how to get rid of themVertically align a tikzpicture and forestDrawing tikz line in the margin for multiple pagesLongtable, contained tikz, padding, custom columns, and an alignment issueTikZ: define arrow starting position based on style and format node labelAlign node name in Tikz