Message Boards Message Boards

0
|
4555 Views
|
1 Reply
|
2 Total Likes
View groups...
Share
Share this post:

Pattern matching in self defined functions

Posted 11 years ago
myCHcc[K_Integer] := Module[{CH}, CH = Drop[Tuples[{0, 1}, K], 1]]
myCHcc[4.4]

myCHccOLD[K_Integer] := Table[IntegerDigits[n, 2, K], {n, 1, 2^K - 1}];
myCHccOLD[4.4]

Hi all,

??am reading the core language
http://www.wolfram.com/learningcenter/tutorialcollection/
where there is an example on page 80.

In the above code,
myCHccOLD[4.4]
is alright. but
myCHccOLD[4.4]
runs into error. I expect the same out like
myCHccOLD[4.4]


What's the difference? I understand tha the two functions creat the same desired outputs. I am asking the differences between the pattern matching on the inputs.


And further,
myCHcc[K_ /; K > 2 ] := Module[{CH}, CH = Drop[Tuples[{0, 1}, K], 1]]


myCHccOLD[K_ /; K > 2 ] :=
  Table[IntegerDigits[n, 2, K], {n, 1, 2^K - 1}];


And using
myCHcc[K_ /; K > 2 ] := Module[{CH}, CH = Drop[Tuples[{0, 1}, K], 1]]

myCHccOLD[K_ /; K > 2 ] :=
  Table[IntegerDigits[n, 2, K], {n, 1, 2^K - 1}];

myCHcc[1]
myCHccOLD[1]
does not give me
myCHcc[1]
myCHccOLD[1]
as the patern does not match the rule of K>2



How do I make sure that the input is an Interger also great 2 at the same time?
myCHcc[K_Integer /; K > 2 ] :=
Module[{CH}, CH = Drop[Tuples[{0, 1}, K], 1]]

Does not do that?
POSTED BY: Casper YC
Check DownValues to see how many different definitions you have created. You will find that the input myCHcc[1] is being intercepted by the one with the pattern _Integer before getting to the one with Conditional /;. By reusing the same function name in the same session with different input patterns, you are in effect overloading the function. This is a common stratagy, but also can be confusing. If overloading is not your intention, be sure to Clear or ClearAll function names before retasking them.
ClearAll[myCHcc]; myCHcc[K_Integer /; K > 2] := Module[{CH}, CH = Drop[Tuples[{0, 1}, K], 1]]
In[ ]:= myCHcc /@ {1, 2, 3}

Out[ ]= {myCHcc[1], myCHcc[2], {{0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}}
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract