MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: TagSet and the listability of Plus[ ]

  • To: mathgroup at
  • Subject: [mg61264] Re: [mg61234] TagSet and the listability of Plus[ ]
  • From: "David Park" <djmp at>
  • Date: Fri, 14 Oct 2005 05:54:02 -0400 (EDT)
  • Sender: owner-wri-mathgroup at


How about something like this?

FooQ[expr_] := MatchQ[expr, {_Integer, _String}]
f1 = {3, "bar"};
f2 = {4, "tick"};
f3 = {1, "one"};

CirclePlus[args__?FooQ] := 
  Fold[{First[#1] + First[#2], Last[#1] <> Last[#2]} &, {0, ""}, {args}]

f1 \[CirclePlus] f2 \[CirclePlus] f3
{8, bartickone}

David Park
djmp at 

From: Trevor Baca [mailto:trevorbaca at]
To: mathgroup at

This is a question about overriding Plus[ ] for a particular type of

Say you define a foo to be the list of an integer and a string:

   FooQ[expr_] := MatchQ[expr, {_Integer, _String}].

Then, for example, with ...

   f1 = {3, "bar"};
   f2 = {4, "tick"};

... we see that Plus[ ] does what it always does and threads across
lists ...

   f1 + f2
   {4, bar+tick}.

But let's say that we want to define addition on foo as the arithmetic
sum of the *first* parts but with the string join of the *second*
parts. Here's a not terribly successful strategy with TagSet:

   Plus /: m_?FooQ + n_?FooQ := {First[m] + First[n],
StringJoin[Last[m], Last[n]]};

This interprets correctly and we see

   {HoldPattern[m_?FooQ + n_?FooQ] :> {First[m] + First[n], Last[m] <>

However, when we try ...

  f1 + f2

... we get ...

   {7, bar+tick}

... rather than ...

  {7, bartick}

... unfortunately.

I'm pretty sure the reason for this is that the interpreter looks at f1
+ f2 and immediately produces the full form ...

   List[7, Plus["bar", "tick"]]

... which means that the clever downvalue for Plus[ ] does absolutely

A reasonable solution is to use a head other than list, as in

  foo[3, bar] + foo[4, tick]

... in which case upvalues work fine:

  foo[a_, b_] + foo[j_, k_] ^:= foo[a+j, StringJoin[b, k]].

But now I've developed something of a small obsession to override Plus
without introducing a special head.

Any suggestions?

  • Prev by Date: Re: challenge problem
  • Next by Date: Re: challenge problem
  • Previous by thread: Re: TagSet and the listability of Plus[ ]
  • Next by thread: Re: Language vs. Library why it matters