1
$\begingroup$

How can I specify a pattern for an expression f for which say f[x,y] returns a value, ie is defined as a function taking two arguments.

let's say I have:

F[f_,l_List?MatrixQ]:= Map[f,l] 

and I want to make sure that f is indeed a function returning values for an input of a certain pattern. say a list or a pair of numbers. How can I do that?

corollary question:

The definition function:

?myfunction

returns a list of substitution rules assigned to myfunction expression. Where does this function look up the these rules from? Is that Internal to Mathematica?

$\endgroup$
  • $\begingroup$ Why? You want the result of F to be a list of numbers? $\endgroup$ – J. M. will be back soon Feb 14 '16 at 1:28
  • 3
    $\begingroup$ You can't generally do that in Mathematica. You basically ask for a type system / signatures, and Mathematica is an untyped language. You can't know in advance whether a given expression would evaluate on a given input to certain type or form of expression.The only real way of doing this kind of thing that comes to my mind would be to introduce your own datatype like MyFunction, and perform post-condition tests during such function's application, throwing an exception or returning $Failed for errors, but that's still a run-time check only, plus the user would have to use this new datatype. $\endgroup$ – Leonid Shifrin Feb 14 '16 at 2:03
  • 1
    $\begingroup$ Related: Function that counts the number of arguments of other functions $\endgroup$ – jkuczm Feb 14 '16 at 10:28
  • 1
    $\begingroup$ As to how you can see evaluation rules defined for a symbol: What is the distinction between DownValues, UpValues, SubValues, and OwnValues? $\endgroup$ – jkuczm Feb 14 '16 at 10:45
  • 1
    $\begingroup$ @Shb No we can't. In general, constructing such a check would require the full evaluation of an expression, which would destroy the purpose of this check. I think, you are mixing run-time information with invocation - time information. At the time when the function is invoked, you generally can't get the sort of information you ask for, unless you define your own type system, with your own function type etc. You can do this, but it will be a lot of work (since it's not integrated into the language, you'll have to reimplement a lot). And it will also slow down the code, perhaps significantly. $\endgroup$ – Leonid Shifrin Feb 14 '16 at 14:16

Browse other questions tagged or ask your own question.