10
$\begingroup$

Bug introduced in 9.0 or earlier, partially fixed in 10.1 and persisting through 11.3


[CASE: 4075992] confirmed

Note: See (72290) for the fixed part of the bug.

Consider the following example:

bar[PatternSequence[a_Symbol, b_String: ""]] := {{a}, {b}}

bar[a]
bar[a, "b"]
(* bar[a] *) (* EXPECTED: {{a}, {""}}*)
(* {{a}, {"b"}} *)

Note how the first example does not evaluate, meaning the Optional value for b doesn't match for some reason. What's stranger is that the following does work (The only difference being the use of _String instead of _Symbol):

bar2[PatternSequence[a_String, b_String: ""]] := {{a}, {b}}

bar2["a"]
bar2["a", "b"]
(* {{"a"}, {""}} *)
(* {{"a"}, {"b"}} *)

While I'm pretty sure this is a bug (I've submitted a bug report already, but please do correct me if I'm wrong), I am in need of a workaround, which is one of the reasons I'm also posting it here.

For reference, what I'm really trying to do (because the above example does not make any sense) is something like the following:

pat = _Integer | PatternSequence[_Symbol | _String, _String : ""]

bar[p : pat] := {p}

bar[1]
bar[a]
bar["a"]
bar["a", "b"]
bar[a, "b"]
(* {1} *)
(* bar[a] *) (* EXPECTED: {a} *)
(* {"a"} *)
(* {"a", "b"} *)
(* {a, "b"} *)

(With pat used in several definitions)

$\endgroup$
  • 1
    $\begingroup$ this is probably not you want but, pat =_Integer | PatternSequence[_Symbol | _String, s___String : ""]/; Length[{s}]<=1 gives the expected result. $\endgroup$ – kglr Jun 6 '18 at 8:47
  • $\begingroup$ @kglr No, that should work perfectly fine in my case, thanks a lot! But it looks like the Optional part in your pattern does not apply in the problematic cases, so it can be left away (luckily, this doesn't matter for me, as I'm handling the default values later on) $\endgroup$ – Lukas Lang Jun 6 '18 at 8:57
  • $\begingroup$ In v10.0.2 bar[a, "b"] won't evaluate either. $\endgroup$ – Szabolcs Jun 6 '18 at 14:53
  • 1
    $\begingroup$ @Szabolcs That's also what I have found - as far as I can tell, this is the bug described in the linked question which has been fixed in 10.1. So the question is now whether this bug here should be considered to have been introduced in 10.1 or whether it has just existed alongside the linked one before. $\endgroup$ – Lukas Lang Jun 6 '18 at 14:56
  • 1
    $\begingroup$ The bug described here is present in 9.0 on Windows, I just tested $\endgroup$ – user6014 Jun 6 '18 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.