3
$\begingroup$

Possible Duplicate:
How to avoid returning a Null if there is no “else” condition in an If contruct

I know there are other ways to solve this problem. Just because I'm curious I tried:

Map[If[# == 1, , #] &, {2, 1, 3, 1, 4}]

This should return a list without the value 1, because when the statement is true it should do nothing. The solution should be:

{2,3,4}

and not

{2,Null,3,Null,4}

Why is it not working as I expect?

$\endgroup$
7
  • $\begingroup$ DeleteCases[{2, 1, 3, 1, 4},1] $\endgroup$
    – ssch
    Commented Dec 21, 2012 at 10:03
  • $\begingroup$ thank you ssch. I know that this works. Just wanted to know if there is a possibility to get the solution out of the if directly. $\endgroup$
    – RMMA
    Commented Dec 21, 2012 at 10:06
  • 2
    $\begingroup$ Map[If[# == 1, Unevaluated[Sequence[]], #] &, {2, 1, 3, 1, 4}] in that case :) $\endgroup$
    – ssch
    Commented Dec 21, 2012 at 10:08
  • 1
    $\begingroup$ Frink, please try to make an effort to find existing questions which address your problem before asking a new one. In this case a search for "If Null" would have brought up the proper question as the first result. $\endgroup$
    – Mr.Wizard
    Commented Dec 21, 2012 at 15:03
  • $\begingroup$ Another duplicate: mathematica.stackexchange.com/q/3447/5 $\endgroup$
    – rm -rf
    Commented Dec 21, 2012 at 15:50

1 Answer 1

8
$\begingroup$

Your If statement is actually

If[# == 1, Null, #]

so it is working perfectly. Try evaluating

Hold@Map[If[# == 1, , #] &, {2, 1, 3, 1, 4}]

to see for yourself. To get what you want, try

Map[If[# == 1, Unevaluated@Sequence[], #] &, {2, 1, 3, 1, 4}]
$\endgroup$
4
  • $\begingroup$ thx, exactly what I was looking for :-) $\endgroup$
    – RMMA
    Commented Dec 21, 2012 at 10:22
  • 1
    $\begingroup$ Maybe mentioning If[x > 1, , 2] // FullForm, which evaluates to If[Greater[x, 1], Null, 2], is also useful $\endgroup$
    – acl
    Commented Dec 21, 2012 at 10:31
  • 1
    $\begingroup$ Incidentally, Unevaluated@Sequence[] can be replaced with ##&[] which I call a "vanishing function." $\endgroup$
    – Mr.Wizard
    Commented Dec 21, 2012 at 15:01
  • $\begingroup$ @Mr.Wizard. ##&[] is a neat trick! $\endgroup$
    – m_goldberg
    Commented Dec 21, 2012 at 17:21

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