I hava a Module in which a want to give a single String or a List as a parameter and I want to change a single String to a List containing this String. So I did the following:

test[in_] := Module[{},
  If[Head[in] == String, {in}, in]

Now test["a"] works fine, but test[{"a","b"}] not, it returns the If statement.

If[List == String, {{"a", "b"}}, {"a", "b"}]

Can anyone give me a hint why this is so and.. how to fix it?

  • 7
    $\begingroup$ Change == to ===. $\endgroup$ – corey979 Jan 7 '18 at 13:37
  • $\begingroup$ @corey979: Thanks! This works. Any explanation why the ==returns the If-Statement? $\endgroup$ – mgamer Jan 7 '18 at 13:44
  • $\begingroup$ Check out the tutorial for Conditionals: The equation List == String is seen as indeterminate; in that case the If[...] statement is returned unevaluated, as the equation will not evaluate to either True or False. $\endgroup$ – gwr Jan 7 '18 at 14:24
  • 1
    $\begingroup$ @mgamer Because == is for math, not for comparing expressions. You need to be able to write equations like x == y and pass them to Solve. Sadly, Wolfram themselves are guilty of misusing == many times in the documentation ... so it's not a surprise if you were confused. $\endgroup$ – Szabolcs Jan 7 '18 at 15:21
  • 4
    $\begingroup$ It's remarkable that such an example is not in the documentation for either If or Equal. It seems a common mistake. I've made it several times, even after learning the difference (e.g. If[OptionValue["Foo"] == Automatic,...]). $\endgroup$ – Michael E2 Jan 7 '18 at 17:00

The Mathematica evaluator is designed to discriminate on the heads of arguments on request, and can do it faster than an If coded inside an unnecessary Module. Write it this way.

test[in_String] := {in}
test[in___] := in


test /@ test /@ {42, "foo", Sin, 42 + "foo", <|"foo" -> 42|>}

{42, {"foo"}, Sin, 42 + "foo", <|"foo" -> 42|>}

  • $\begingroup$ Thank you for this answer, the module is, in this case, not unnecessary, I only stripped everything else off, to make a MWE, nevertheless I´mn going to check whether your proposal is the faster implementation. :-) $\endgroup$ – mgamer Jan 7 '18 at 20:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.