Re: A more syntactically compact way?
- To: mathgroup at smc.vnet.net
- Subject: [mg63075] Re: [mg62991] A more syntactically compact way?
- From: Omega Consulting <info at omegaconsultinggroup.com>
- Date: Tue, 13 Dec 2005 03:41:06 -0500 (EST)
- References: <200512101103.GAA29343@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
I don't think there's a more compact way, assuming you want the
definition attached to foo.
However, if you're have several of these functions, you can create a
utility to make it easier.
In[1]:=fooQ[f_] := MatchQ[f, foo[_Integer, _Integer]]
In[2]:=Attributes[FooFunction] = {HoldAll};
Ignore the warning here.
In[3]:=FooFunction[function_, var_, definition_] :=
(foo /: function[var_foo?fooQ] := definition)
During evaluation of In[3]:=
RuleDelayed::"rhs": "Pattern var_foo appears on the right-hand side
of rule \
FooFunction[function_, var_, definition_] :> (foo /: function[var_foo?
fooQ] \
:= definition). More?"
In[4]:=FooFunction[jiggle, f, First[f]^Last[f]]
In[5]:=jiggle[foo[2, 3]]
Out[5]=8
Another strategy might be to have a constructor for your type.
CreateFoo[x_Integer, y_Integer] := foo[x,y]
In theory, if users only use the constructor, you can guarantee the
type is well-formed just with a head test. And you don't need a fooQ.
Ofcourse, you'll need to hide the internal representation to prevent
people by-passing the constructor. Something along the lines of:
MakeBoxes[foo[x_, y_], form_] := "-foo-"
----------------------------------------------
Omega Consulting
The final answer to your Mathematica needs.
http://omegaconsultinggroup.com
On Dec 10, 2005, at 5:03 AM, Trevor Baca wrote:
> This is a question about using assigning an upvalue to a symbol and
> "type"-checking the symbol with some sort of Q predicate:
>
> If we define a "type" with the predicate ...
>
> fooQ[f_] := MatchQ[f, foo[_Integer, _Integer]]
>
> ... then assigning an upvalue this way doesn't work ...
>
> foo /: jiggle[f_?fooQ] := First[f]^Last[f]
> TagSetDelayed::tagnf: Tag foo not found in jiggle[f_?fooQ]
>
> ... and assigning an upvalue this way ....
>
> foo /: jiggle[f_foo] := First[f]^Last[f]
>
> ... does (syntactically) work, but at the cost of checking only the
> *head* but not the "type".
>
> So, to both successfully assign the upvalue AND check "type", I
> usually
> use something like:
>
> foo /: bar[f_foo?fooQ] := First[f] * Last[f]
>
> which works fine.
>
> Question: is there a syntactically more compact solution?
>
>
> Trevor.
- References:
- A more syntactically compact way?
- From: "Trevor Baca" <trevorbaca@gmail.com>
- A more syntactically compact way?