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


I get expected result


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]
  • 6
    $\begingroup$ Use :> instead of ->. $\endgroup$ Commented 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$ Commented May 13, 2016 at 10:30
  • $\begingroup$ @E.Doroskevic But c should not match the pattern x_List or does it match? $\endgroup$
    – tom
    Commented 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$ Commented 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$ Commented May 13, 2016 at 11:03

1 Answer 1

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

{a, c}


Your Answer

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

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