2
$\begingroup$

When I use ReplaceAll to replace date objects, I find there will be an error which wouldn't appear when not in the ReplaceAll enviroment. For example:

In[257]:= z1 = 
 DateObject[{2008, 4, 27, 9, 0, 0.}, "Instant", "Gregorian", 8.]

Out[257]= DateObject[{2008, 4, 27, 9, 0, 
  0.}, "Instant", "Gregorian", 8.]

In[258]:= z1[[1]]

Out[258]= {2008, 4, 27, 9, 0, 0.}

In[259]:= {5, z1, 6, 7} /. zz_?DateObjectQ -> zz[[1]][[4]]

During evaluation of In[259]:= Part::partd: Part specification zz[[1]] is longer than depth of object.

During evaluation of In[259]:= Part::partw: Part 4 of zz[[1]] does not exist.

Out[259]= {5, 9, 6, 7}
$\endgroup$

1 Answer 1

4
$\begingroup$

Use RuleDelayed to avoid error messages

{5, z1, 6, 7} /. zz_?DateObjectQ :> zz[[1]][[4]]

RuleDelayed localises zz and prevents its attempted evaluation on the RHS of the rule. "RuleDelayed has the attribute HoldRest." - docs.

Without RuleDelayed you are effectively trying to evaluate

zz[[1]][[4]]

Part::partd: Part specification zz[[1]] is longer than depth of object.

etc.

$\endgroup$
10
  • $\begingroup$ Why should use RuleDelayed here? I don't understand. $\endgroup$
    – Y. zeng
    Commented Nov 14, 2022 at 12:40
  • $\begingroup$ zz is an date object, so zz[[1]][[4]] should be right? I still don't know need RuleDelay. $\endgroup$
    – Y. zeng
    Commented Nov 14, 2022 at 12:46
  • $\begingroup$ z1 is a date object. When you get to the rule zz_ -> zz[[1]][[4]] the last part: zz[[1]][[4]] is evaluated before the rule is applied. Use RuleDelayed, which has attribute HoldFirst to hold evaluation of zz[[1]][[4]] until after the rule is applied. $\endgroup$ Commented Nov 14, 2022 at 12:49
  • $\begingroup$ Before the rule is applied, why evaluating of zz[[1]][[4]] will cause error? $\endgroup$
    – Y. zeng
    Commented Nov 14, 2022 at 12:51
  • $\begingroup$ because zz is just a symbol at that stage, not a date object. $\endgroup$ Commented Nov 14, 2022 at 12:52

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