Message Boards Message Boards

0
|
3150 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Difference between SetDelayed and Function

Posted 3 years ago

I am studying the Wolfram language, and in the guides I came across the method to define a function, for example:

f[x_] := x^2
Head[f]
(*Symbol*)

Which is nice, f is defined just as, for example, Sin and Sqrt are:

Head[Sqrt] (*Symbol*)
Head[Sin] (*Symbol*)

I also noticed this use of Function, in a guide about Pure Functions:

g=Function[x,x^2]
Head[g]
(*Function*)

What's is the difference between the two? Which one is preferred, and when?

A non similarity, as an example: One can define f to accept only Integers:

f[x_Integer] := x^2

But it is a bit harder to do that for a Pure function.

POSTED BY: Ehud Behar
2 Replies
Posted 3 years ago

In my style of writing WL, I typically use pure functions inline, without assigning them to a name, as when writing the function argument to Map. For functions that I want to be part of my package, I use function definitions (the SetDelayed option).

Function definitions are generally my go-to default, because they have many advantages: * pattern-matching, which you mentioned; this doubles as a sort of documentation for the function, similar to the way types can hint at how to use a function * attributes (Protected, HoldAll) can be assigned to a symbol; there is a way to assign attributes to pure functions but I find the syntax awkward and can't recall ever having done it * because of the function definitions use pattern-matching, it lends itself to writing overloads of a function, which I use a lot

Pure functions, when used anonymously (without assigning them to a simple), are good when a relatively simple transformation needs to be done, as with Map, Fold, or SortBy (or any of the other *By functions). Although even with Map and Fold I sometimes find the function gets bigger than I first expected, and I move it to be a function definition assigned to a named symbol.

POSTED BY: Joel Klein
Posted 3 years ago

Thanks a lot for your reply!!

I shall come back to your explanations in the future when facing the subjects you mentioned (My coding experience is not at this level at the moment).

POSTED BY: Ehud Behar
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract