3
$\begingroup$

I have a list whose elements are (symbol or list) and I would like to replace the inner lists by their first elements. I do this

f[list_] := Replace[ list , x_List -> First[x], 1 ]

If I test it

f[{{a,b},c}]

I get expected result

{a,c}

But I get an error too

First::normal: "Nonatomic expression expected at position 1 in First[x].

Why do I get the error?


edit: I can alter the definition of f such that I do not get the error, but I still do not understand why I got the error in the first place.

version 1:(based on J.M. comment)

f[list_] := Replace[list, x_List :> x, 1]

version 2:

f[list_] := Replace[list, {x_, (_) ...} -> x, 1]
$\endgroup$
6
  • 6
    $\begingroup$ Use :> instead of ->. $\endgroup$ May 13, 2016 at 10:16
  • $\begingroup$ You get this error message when you apply function First to element c like such First @ c since c is an atomic element there is nothing to apply First to $\endgroup$ May 13, 2016 at 10:30
  • $\begingroup$ @E.Doroskevic But c should not match the pattern x_List or does it match? $\endgroup$
    – tom
    May 13, 2016 at 10:49
  • $\begingroup$ It doesn't match, yes, but you are using Rule instead of RuleDelayed. One evaluates its right-hand side at once; the other doesn't. $\endgroup$ May 13, 2016 at 11:01
  • $\begingroup$ @tom you can see more information about it here in the documentation: reference.wolfram.com/language/ref/Rule.html check Background & Context. 2nd paragraph $\endgroup$ May 13, 2016 at 11:03

1 Answer 1

3
$\begingroup$
f2[l_] := # & @@@ l;
f2[{{a, b}, c}]

{a, c}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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