Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== In D == [[D (programming language)|D]] provides several ways to declare function objects: Lisp/Python-style via [[closure (computer science)|closures]] or C#-style via [[delegate (CLI)|delegate]]s, respectively: <syntaxhighlight lang="d"> bool find(T)(T[] haystack, bool delegate(T) needle_test) { foreach (straw; haystack) { if (needle_test(straw)) return true; } return false; } void main() { int[] haystack = [345, 15, 457, 9, 56, 123, 456]; int needle = 123; bool needleTest(int n) { return n == needle; } assert(find(haystack, &needleTest)); } </syntaxhighlight> The difference between a [[delegate (CLI)|delegate]] and a [[closure (computer science)|closure]] in D is automatically and conservatively determined by the compiler. D also supports function literals, that allow a lambda-style definition: <syntaxhighlight lang="d"> void main() { int[] haystack = [345, 15, 457, 9, 56, 123, 456]; int needle = 123; assert(find(haystack, (int n) { return n == needle; })); } </syntaxhighlight> To allow the compiler to inline the code (see above), function objects can also be specified C++-style via [[operator overloading]]: <syntaxhighlight lang="d"> bool find(T, F)(T[] haystack, F needle_test) { foreach (straw; haystack) { if (needle_test(straw)) return true; } return false; } void main() { int[] haystack = [345, 15, 457, 9, 56, 123, 456]; int needle = 123; class NeedleTest { int needle; this(int n) { needle = n; } bool opCall(int n) { return n == needle; } } assert(find(haystack, new NeedleTest(needle))); } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)