0
$\begingroup$

This question already has an answer here:

Why would this work

Times[a, b, c, d] /. Times :> List
(* {a, b, c, d} *)

but this doesn't work (the Times still remains even when the List has been added)?

Times[a, b, c, d] /. Times[p__] :> List[p]
(* {a b c d} *)

Applying Trace shows that Times might have applied itself to p__ before the pattern is matched, so that the expression now became just a b c d/. p__:>{p}. If that's the case, why would Times[p__] become p__?

Times[a, b, c, d] /. Times[p__] :> List[p] // Trace
(* {{{Times[p__],p__},p__:>{p},p__:>{p}},a b c d/. p__:>{p},{a b c d}} *)
$\endgroup$

marked as duplicate by Mr.Wizard Jul 21 '14 at 6:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ Times[p__] directly evaluates to p__. You need HoldPattern, Verbatim, or a dummy pattern: (x:Times)[p__]. This question is a duplicate. I am looking now. $\endgroup$ – Mr.Wizard Jul 21 '14 at 6:03
  • 1
    $\begingroup$ Please also see: (23066), (25476), (30152) $\endgroup$ – Mr.Wizard Jul 21 '14 at 6:09
  • 1
    $\begingroup$ For clarity, all of these work: Times[a, b, c, d] /. HoldPattern[Times[p__]] :> List[p] -- Times[a, b, c, d] /. HoldPattern[Times][p__] :> List[p] -- Times[a, b, c, d] /. Verbatim[Times][p__] :> List[p] -- Times[a, b, c, d] /. (x : Times)[p__] :> List[p] $\endgroup$ – Mr.Wizard Jul 21 '14 at 6:12
  • $\begingroup$ Bravo @Mr.Wizard! I learned something new today (HoldPattern) from you. $\endgroup$ – seismatica Jul 21 '14 at 6:13
  • $\begingroup$ Glad I could help. :-) By the way, while it doesn't answer this question you could also use: Times[a, b, c, d] /. p_Times :> List @@ p. However, be aware that this relies on evaluation of the righ-hand-side, meaning that it won't work inside a Hold: Hold[Times[a, b, c, d]] /. p_Times :> List @@ p outputs Hold[List @@ (a b c d)] $\endgroup$ – Mr.Wizard Jul 21 '14 at 6:18

Browse other questions tagged or ask your own question.