Overloading functions for different types of parameters is very powerful. I can easily write different versions of a function depending on the function parameters being Integer, Real, Complex, Sring List and so on.
Now I want to write function which operates on data structures looking like this:
{_String, _List}
Example: {"my data structure", {1,2,3,4,5}}
My function shall also operate either
- two strings (containing file names) plus an optional third one which can be either "CSV" or "TSV"
Examples: f["file1","fiel2"]
or f["file1","fiel2","TSV"]
or on
- an arbitrary number>2 of strings (containing file names but neither "CSV" or "TSV") plus an optional last parameter which can be either "CSV" or "TSV"
Examples: f["file1","fiel2","file3"]
or f["file1","fiel2","file3","TSV"]
- or a string (containing a file name) as first parameter, a data structure of the type described above as second one plus an optional third one which can be either "CSV" or "TSV"
Examples: f["file1",{"my data structure", {1,2,3}}]
or f["file1",{"my data structure", {1,2,3}}, "CSV"]
I did it like this:
Remove[f];
dataStruct={_String, _List};
f[a_String, b_String, type_:"CSV"]:=Print["1. variant with two Strings, type=", type];
f[a_String, b:dataStruct, type_:"CSV"]:=Print["2. variant with String and dataStruct, type=", type];
f[a:dataStruct, b:dataStruct, type_:"CSV"]:=Print["3. variant with two dataStruct, type=", type];
f[{a_String, b_String, ___String}, type_:"CSV"]:=Print["4. variant with List of Strings, type=", type];
f["foo", "bar"]
f["foo", "bar", "CSV"]
work as expected.
f["foo", "bar", "metrics"]
returns the last parameter "metrics" as type instead of matching the fourth definition.
f["foo", {"bar", {}}]
f["foo", {"bar", {}}, "CSV"]
invoke the second definition
f[{"foo", {1, 2}}, {"bar", {3, 4, 5}}]
takes the third variant.
How can I cope with this?
List
in your"metrics"
example? $\endgroup$f[{"foo", "bar", "metrics"}]
andf[{"foo", "bar", "metrics"}, "CSV"]
use the fourth definition! $\endgroup$