1

Possible Duplicate:
Why doesn’t PatternTest work with Composition?

I'd like my function to only evaluate when the argument is a list of pairs. It seems like Repeated and a question mark should work:

fourPears[argument_?MatchQ[#, {{_, _} ..}] &]

but it does not. What's wrong with this?

ArgentoSapiens
  • 7,780
  • 1
  • 32
  • 49
  • The question mark is called PatternTest in this context and is not to be confused with Information, which also has a question mark as its short form. – ArgentoSapiens Dec 10 '12 at 23:22

2 Answers2

2

I prefer the simpler pattern pairs : {{_, _} ..}. For example,

f[pairs : {{_, _} ..}] := Row[{pairs, " is a list of pairs"}]

f@a

f[a]

f@{a}

f[{a}]

f@{a, b, {c, d}}

f[{a, b, {c, d}}]

f@{{a, w}, {b, x}, {c, y}}

{{a, w}, {b, x}, {c, y}} is a list of pairs

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
1

The ? in this expression (does it have a name?) has high precedence, so it sticks to argument_ and MatchQ more than MatchQ sticks to its own arguments. You need parentheses.

fourPears[argument_?(MatchQ[#, {{_, _} ..}] &)]

should work, but it might not be the best way to accomplish this.

ArgentoSapiens
  • 7,780
  • 1
  • 32
  • 49