Group Abstract Group Abstract

Message Boards Message Boards

0
|
417 Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

How does set delay function?

Posted 1 month ago

Does set delay assign the expression on the left-hand side to the right-hand side but does not compile until the arguments are passed through the function name/head?

Am I missing something from this understanding of set delay or is there more to it? Thank you in advance.

3 Replies

One commin pitfall:

f1[x_] = D[x^3, x];
f2[x_] := D[x^3, x];
f1[5]
f2[5]

Another example where the difference between immediate and delayed evaluation is very clear:

g1[x_] = x + RandomReal[];
g2[x_] := x + RandomReal[];
{g1[5], g1[5], g1[5]}
g1[5] == g1[5]
Plot[g1[x], {x, -1, 1}]
{g2[5], g2[5], g2[5]}
g2[5] == g2[5]
Plot[g2[x], {x, -1, 1}]
POSTED BY: Gianluca Gorni
Posted 1 month ago

Just augmenting Michael Rogers' answer with an example:

x = 7;
func1[x_] := x^2; (* SetDelayed used here. *)
func2[x_] = x^2; (* Set used here. *)

We can see the difference immediately in the DownValues.

DownValues[func1]
(* {HoldPattern[func1[x_]] :> x^2} *)

DownValues[func2]
(* {HoldPattern[func2[x_]] :> 49} *)

We can see the difference by tracing evaluation.

Trace[func1[2]]
(* {func1[2], 2^2, 4} *)

Trace[func2[2]]
(* {func2[2], 49} *)

In func1, the right hand side was not evaluated before creating DownValues. In func2 the right hand side was evaluated before creating DownValues.

POSTED BY: Eric Rimbey

Short answer to the first question: Yes.

Short to the second question: IDK.

Let's assume the reader understands the tech note Evaluation of Expressions. If so, one understands that the evaluation of an expression is done by applying a replacement rule, pattern :> value. After replacement, value is evaluated in the same way. What SetDelayed[pattern,value] does is create a replacement rule, called a down-value, in which the expression value is stored in its literal (or unevaluated or uncompiled) form. For the simple example below note that 2^3 is stored as 2^3, not as 8.

func[x_] := 2^3;   (* same as SetDelayed[func[x_], 2^3] *)
DownValues[func]
(*     {HoldPattern[func[x_]] :> 2^3}    *)

The full definition of func consists of several lists of replacement rules. For this simple example, most of the lists are empty, and there is only one down-value. One can look up the other kinds of values in the documentation.

Language`ExtendedFullDefinition[func]
(*
Language`DefinitionList[HoldForm[func] -> {
   OwnValues -> {},
   SubValues -> {},
   UpValues -> {},
   DownValues -> {HoldPattern[func[x_]] :> 2^3},
   NValues -> {},
   FormatValues -> {},
   DefaultValues -> {},
   Messages -> {},
   Attributes -> {}}]
*)
POSTED BY: Michael Rogers
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard