Group Abstract Group Abstract

Message Boards Message Boards

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

How does set delay function?

Posted 6 months 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 6 months 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
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