Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It is possible to put filters on function arguments, e.g., the definition

    f[x_Integer] := ...
will define a rule for f[] that only matches expressions where the argument to f[] has the head "Integer". It is even possible to use arbitrary predicates:

    vec3Q[v_] := VectorQ[v, NumberQ]&&Length[v]==3
    f[v_?vec3Q] := ...
This lets you sort-of have type-checking. This is entirely opt-in, so you have to be somewhat rigorous about its use or it does not do any good. Also, in practice if any invocation of f[] does not have arguments which match the types for which you have defined it, the expression just remains unevaluated, which can create a mess (but maybe less of a mess than evaluating the function on input of the wrong form). The performance impact (particularly of the predicate version) is also non-zero, but my experience is that the biggest performance limitations come from trying to keep your machine from grinding to a halt when a runaway expression applied to the wrong thing explodes in complexity and eats all of your RAM... and this helps avoid that.

While I have found this to be very helpful for writing and debugging hairy expressions, I used Mathematica for years before I even knew this was a thing. In reality almost no one does this, certainly not with any consistency, and the situation is as bad as you fear it would be.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: