CINXE.COM

Closure (computer programming) - Wikipedia

<!DOCTYPE html> <html class="client-nojs vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-sticky-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-feature-night-mode-enabled skin-theme-clientpref-day vector-toc-available" lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Closure (computer programming) - Wikipedia</title> <script>(function(){var className="client-js vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-sticky-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-feature-night-mode-enabled skin-theme-clientpref-day vector-toc-available";var cookie=document.cookie.match(/(?:^|; )enwikimwclientpreferences=([^;]+)/);if(cookie){cookie[1].split('%2C').forEach(function(pref){className=className.replace(new RegExp('(^| )'+pref.replace(/-clientpref-\w+$|[^\w-]+/g,'')+'-clientpref-\\w+( |$)'),'$1'+pref+'$2');});}document.documentElement.className=className;}());RLCONF={"wgBreakFrames":false,"wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"dmy", "wgMonthNames":["","January","February","March","April","May","June","July","August","September","October","November","December"],"wgRequestId":"bac690ff-6be6-4966-9100-1f19e9bccd1e","wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"Closure_(computer_programming)","wgTitle":"Closure (computer programming)","wgCurRevisionId":1246240241,"wgRevisionId":1246240241,"wgArticleId":62319,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Articles with short description","Short description matches Wikidata","Use dmy dates from August 2020","All articles with unsourced statements","Articles with unsourced statements from December 2014","Articles with unsourced statements from September 2011","Articles with example C++ code","Articles with example C Sharp code","Articles with example D code","Articles with example Eiffel code","Articles with example Haskell code", "Articles with example Java code","Articles with example JavaScript code","Articles with example Objective-C code","Articles with example Python (programming language) code","Articles with example Ruby code","Articles with example Scheme (programming language) code","Articles with example Smalltalk code","Programming language concepts","Implementation of functional programming languages","Subroutines"],"wgPageViewLanguage":"en","wgPageContentLanguage":"en","wgPageContentModel":"wikitext","wgRelevantPageName":"Closure_(computer_programming)","wgRelevantArticleId":62319,"wgIsProbablyEditable":true,"wgRelevantPageIsProbablyEditable":true,"wgRestrictionEdit":[],"wgRestrictionMove":[],"wgRedirectedFrom":"Closure_(computer_science)","wgNoticeProject":"wikipedia","wgCiteReferencePreviewsActive":false,"wgFlaggedRevsParams":{"tags":{"status":{"levels":1}}},"wgMediaViewerOnClick":true,"wgMediaViewerEnabledByDefault":true,"wgPopupsFlags":0,"wgVisualEditor":{"pageLanguageCode":"en", "pageLanguageDir":"ltr","pageVariantFallbacks":"en"},"wgMFDisplayWikibaseDescriptions":{"search":true,"watchlist":true,"tagline":false,"nearby":true},"wgWMESchemaEditAttemptStepOversample":false,"wgWMEPageLength":50000,"wgInternalRedirectTargetUrl":"/wiki/Closure_(computer_programming)","wgRelatedArticlesCompat":[],"wgCentralAuthMobileDomain":false,"wgEditSubmitButtonLabelPublish":true,"wgULSPosition":"interlanguage","wgULSisCompactLinksEnabled":false,"wgVector2022LanguageInHeader":true,"wgULSisLanguageSelectorEmpty":false,"wgWikibaseItemId":"Q535335","wgCheckUserClientHintsHeadersJsApi":["brands","architecture","bitness","fullVersionList","mobile","model","platform","platformVersion"],"GEHomepageSuggestedEditsEnableTopics":true,"wgGETopicsMatchModeEnabled":false,"wgGEStructuredTaskRejectionReasonTextInputEnabled":false,"wgGELevelingUpEnabledForUser":false};RLSTATE={"ext.globalCssJs.user.styles":"ready","site.styles":"ready","user.styles":"ready","ext.globalCssJs.user":"ready","user": "ready","user.options":"loading","ext.cite.styles":"ready","ext.pygments":"ready","skins.vector.search.codex.styles":"ready","skins.vector.styles":"ready","skins.vector.icons":"ready","ext.wikimediamessages.styles":"ready","ext.visualEditor.desktopArticleTarget.noscript":"ready","ext.uls.interlanguage":"ready","wikibase.client.init":"ready","ext.wikimediaBadges":"ready"};RLPAGEMODULES=["mediawiki.action.view.redirect","ext.cite.ux-enhancements","ext.pygments.view","site","mediawiki.page.ready","mediawiki.toc","skins.vector.js","ext.centralNotice.geoIP","ext.centralNotice.startUp","ext.gadget.ReferenceTooltips","ext.gadget.switcher","ext.urlShortener.toolbar","ext.centralauth.centralautologin","ext.popups","ext.visualEditor.desktopArticleTarget.init","ext.visualEditor.targetLoader","ext.echo.centralauth","ext.eventLogging","ext.wikimediaEvents","ext.navigationTiming","ext.uls.interface","ext.cx.eventlogging.campaigns","ext.cx.uls.quick.actions","wikibase.client.vector-2022", "ext.checkUser.clientHints","ext.growthExperiments.SuggestedEditSession","wikibase.sidebar.tracking"];</script> <script>(RLQ=window.RLQ||[]).push(function(){mw.loader.impl(function(){return["user.options@12s5i",function($,jQuery,require,module){mw.user.tokens.set({"patrolToken":"+\\","watchToken":"+\\","csrfToken":"+\\"}); }];});});</script> <link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=ext.cite.styles%7Cext.pygments%2CwikimediaBadges%7Cext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediamessages.styles%7Cskins.vector.icons%2Cstyles%7Cskins.vector.search.codex.styles%7Cwikibase.client.init&amp;only=styles&amp;skin=vector-2022"> <script async="" src="/w/load.php?lang=en&amp;modules=startup&amp;only=scripts&amp;raw=1&amp;skin=vector-2022"></script> <meta name="ResourceLoaderDynamicStyles" content=""> <link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles&amp;skin=vector-2022"> <meta name="generator" content="MediaWiki 1.44.0-wmf.4"> <meta name="referrer" content="origin"> <meta name="referrer" content="origin-when-cross-origin"> <meta name="robots" content="max-image-preview:standard"> <meta name="format-detection" content="telephone=no"> <meta name="viewport" content="width=1120"> <meta property="og:title" content="Closure (computer programming) - Wikipedia"> <meta property="og:type" content="website"> <link rel="alternate" media="only screen and (max-width: 640px)" href="//en.m.wikipedia.org/wiki/Closure_(computer_programming)"> <link rel="alternate" type="application/x-wiki" title="Edit this page" href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit"> <link rel="apple-touch-icon" href="/static/apple-touch/wikipedia.png"> <link rel="icon" href="/static/favicon/wikipedia.ico"> <link rel="search" type="application/opensearchdescription+xml" href="/w/rest.php/v1/search" title="Wikipedia (en)"> <link rel="EditURI" type="application/rsd+xml" href="//en.wikipedia.org/w/api.php?action=rsd"> <link rel="canonical" href="https://en.wikipedia.org/wiki/Closure_(computer_programming)"> <link rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en"> <link rel="alternate" type="application/atom+xml" title="Wikipedia Atom feed" href="/w/index.php?title=Special:RecentChanges&amp;feed=atom"> <link rel="dns-prefetch" href="//meta.wikimedia.org" /> <link rel="dns-prefetch" href="//login.wikimedia.org"> </head> <body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject mw-editable page-Closure_computer_programming rootpage-Closure_computer_programming skin-vector-2022 action-view"><a class="mw-jump-link" href="#bodyContent">Jump to content</a> <div class="vector-header-container"> <header class="vector-header mw-header"> <div class="vector-header-start"> <nav class="vector-main-menu-landmark" aria-label="Site"> <div id="vector-main-menu-dropdown" class="vector-dropdown vector-main-menu-dropdown vector-button-flush-left vector-button-flush-right" > <input type="checkbox" id="vector-main-menu-dropdown-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-vector-main-menu-dropdown" class="vector-dropdown-checkbox " aria-label="Main menu" > <label id="vector-main-menu-dropdown-label" for="vector-main-menu-dropdown-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet cdx-button--icon-only " aria-hidden="true" ><span class="vector-icon mw-ui-icon-menu mw-ui-icon-wikimedia-menu"></span> <span class="vector-dropdown-label-text">Main menu</span> </label> <div class="vector-dropdown-content"> <div id="vector-main-menu-unpinned-container" class="vector-unpinned-container"> <div id="vector-main-menu" class="vector-main-menu vector-pinnable-element"> <div class="vector-pinnable-header vector-main-menu-pinnable-header vector-pinnable-header-unpinned" data-feature-name="main-menu-pinned" data-pinnable-element-id="vector-main-menu" data-pinned-container-id="vector-main-menu-pinned-container" data-unpinned-container-id="vector-main-menu-unpinned-container" > <div class="vector-pinnable-header-label">Main menu</div> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-pin-button" data-event-name="pinnable-header.vector-main-menu.pin">move to sidebar</button> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-unpin-button" data-event-name="pinnable-header.vector-main-menu.unpin">hide</button> </div> <div id="p-navigation" class="vector-menu mw-portlet mw-portlet-navigation" > <div class="vector-menu-heading"> Navigation </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="n-mainpage-description" class="mw-list-item"><a href="/wiki/Main_Page" title="Visit the main page [z]" accesskey="z"><span>Main page</span></a></li><li id="n-contents" class="mw-list-item"><a href="/wiki/Wikipedia:Contents" title="Guides to browsing Wikipedia"><span>Contents</span></a></li><li id="n-currentevents" class="mw-list-item"><a href="/wiki/Portal:Current_events" title="Articles related to current events"><span>Current events</span></a></li><li id="n-randompage" class="mw-list-item"><a href="/wiki/Special:Random" title="Visit a randomly selected article [x]" accesskey="x"><span>Random article</span></a></li><li id="n-aboutsite" class="mw-list-item"><a href="/wiki/Wikipedia:About" title="Learn about Wikipedia and how it works"><span>About Wikipedia</span></a></li><li id="n-contactpage" class="mw-list-item"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us" title="How to contact Wikipedia"><span>Contact us</span></a></li> </ul> </div> </div> <div id="p-interaction" class="vector-menu mw-portlet mw-portlet-interaction" > <div class="vector-menu-heading"> Contribute </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="n-help" class="mw-list-item"><a href="/wiki/Help:Contents" title="Guidance on how to use and edit Wikipedia"><span>Help</span></a></li><li id="n-introduction" class="mw-list-item"><a href="/wiki/Help:Introduction" title="Learn how to edit Wikipedia"><span>Learn to edit</span></a></li><li id="n-portal" class="mw-list-item"><a href="/wiki/Wikipedia:Community_portal" title="The hub for editors"><span>Community portal</span></a></li><li id="n-recentchanges" class="mw-list-item"><a href="/wiki/Special:RecentChanges" title="A list of recent changes to Wikipedia [r]" accesskey="r"><span>Recent changes</span></a></li><li id="n-upload" class="mw-list-item"><a href="/wiki/Wikipedia:File_upload_wizard" title="Add images or other media for use on Wikipedia"><span>Upload file</span></a></li> </ul> </div> </div> </div> </div> </div> </div> </nav> <a href="/wiki/Main_Page" class="mw-logo"> <img class="mw-logo-icon" src="/static/images/icons/wikipedia.png" alt="" aria-hidden="true" height="50" width="50"> <span class="mw-logo-container skin-invert"> <img class="mw-logo-wordmark" alt="Wikipedia" src="/static/images/mobile/copyright/wikipedia-wordmark-en.svg" style="width: 7.5em; height: 1.125em;"> <img class="mw-logo-tagline" alt="The Free Encyclopedia" src="/static/images/mobile/copyright/wikipedia-tagline-en.svg" width="117" height="13" style="width: 7.3125em; height: 0.8125em;"> </span> </a> </div> <div class="vector-header-end"> <div id="p-search" role="search" class="vector-search-box-vue vector-search-box-collapses vector-search-box-show-thumbnail vector-search-box-auto-expand-width vector-search-box"> <a href="/wiki/Special:Search" class="cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet cdx-button--icon-only search-toggle" title="Search Wikipedia [f]" accesskey="f"><span class="vector-icon mw-ui-icon-search mw-ui-icon-wikimedia-search"></span> <span>Search</span> </a> <div class="vector-typeahead-search-container"> <div class="cdx-typeahead-search cdx-typeahead-search--show-thumbnail cdx-typeahead-search--auto-expand-width"> <form action="/w/index.php" id="searchform" class="cdx-search-input cdx-search-input--has-end-button"> <div id="simpleSearch" class="cdx-search-input__input-wrapper" data-search-loc="header-moved"> <div class="cdx-text-input cdx-text-input--has-start-icon"> <input class="cdx-text-input__input" type="search" name="search" placeholder="Search Wikipedia" aria-label="Search Wikipedia" autocapitalize="sentences" title="Search Wikipedia [f]" accesskey="f" id="searchInput" > <span class="cdx-text-input__icon cdx-text-input__start-icon"></span> </div> <input type="hidden" name="title" value="Special:Search"> </div> <button class="cdx-button cdx-search-input__end-button">Search</button> </form> </div> </div> </div> <nav class="vector-user-links vector-user-links-wide" aria-label="Personal tools"> <div class="vector-user-links-main"> <div id="p-vector-user-menu-preferences" class="vector-menu mw-portlet emptyPortlet" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> </ul> </div> </div> <div id="p-vector-user-menu-userpage" class="vector-menu mw-portlet emptyPortlet" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> </ul> </div> </div> <nav class="vector-appearance-landmark" aria-label="Appearance"> <div id="vector-appearance-dropdown" class="vector-dropdown " title="Change the appearance of the page&#039;s font size, width, and color" > <input type="checkbox" id="vector-appearance-dropdown-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-vector-appearance-dropdown" class="vector-dropdown-checkbox " aria-label="Appearance" > <label id="vector-appearance-dropdown-label" for="vector-appearance-dropdown-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet cdx-button--icon-only " aria-hidden="true" ><span class="vector-icon mw-ui-icon-appearance mw-ui-icon-wikimedia-appearance"></span> <span class="vector-dropdown-label-text">Appearance</span> </label> <div class="vector-dropdown-content"> <div id="vector-appearance-unpinned-container" class="vector-unpinned-container"> </div> </div> </div> </nav> <div id="p-vector-user-menu-notifications" class="vector-menu mw-portlet emptyPortlet" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> </ul> </div> </div> <div id="p-vector-user-menu-overflow" class="vector-menu mw-portlet" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="pt-sitesupport-2" class="user-links-collapsible-item mw-list-item user-links-collapsible-item"><a data-mw="interface" href="https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en" class=""><span>Donate</span></a> </li> <li id="pt-createaccount-2" class="user-links-collapsible-item mw-list-item user-links-collapsible-item"><a data-mw="interface" href="/w/index.php?title=Special:CreateAccount&amp;returnto=Closure+%28computer+programming%29" title="You are encouraged to create an account and log in; however, it is not mandatory" class=""><span>Create account</span></a> </li> <li id="pt-login-2" class="user-links-collapsible-item mw-list-item user-links-collapsible-item"><a data-mw="interface" href="/w/index.php?title=Special:UserLogin&amp;returnto=Closure+%28computer+programming%29" title="You&#039;re encouraged to log in; however, it&#039;s not mandatory. [o]" accesskey="o" class=""><span>Log in</span></a> </li> </ul> </div> </div> </div> <div id="vector-user-links-dropdown" class="vector-dropdown vector-user-menu vector-button-flush-right vector-user-menu-logged-out" title="Log in and more options" > <input type="checkbox" id="vector-user-links-dropdown-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-vector-user-links-dropdown" class="vector-dropdown-checkbox " aria-label="Personal tools" > <label id="vector-user-links-dropdown-label" for="vector-user-links-dropdown-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet cdx-button--icon-only " aria-hidden="true" ><span class="vector-icon mw-ui-icon-ellipsis mw-ui-icon-wikimedia-ellipsis"></span> <span class="vector-dropdown-label-text">Personal tools</span> </label> <div class="vector-dropdown-content"> <div id="p-personal" class="vector-menu mw-portlet mw-portlet-personal user-links-collapsible-item" title="User menu" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="pt-sitesupport" class="user-links-collapsible-item mw-list-item"><a href="https://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&amp;utm_medium=sidebar&amp;utm_campaign=C13_en.wikipedia.org&amp;uselang=en"><span>Donate</span></a></li><li id="pt-createaccount" class="user-links-collapsible-item mw-list-item"><a href="/w/index.php?title=Special:CreateAccount&amp;returnto=Closure+%28computer+programming%29" title="You are encouraged to create an account and log in; however, it is not mandatory"><span class="vector-icon mw-ui-icon-userAdd mw-ui-icon-wikimedia-userAdd"></span> <span>Create account</span></a></li><li id="pt-login" class="user-links-collapsible-item mw-list-item"><a href="/w/index.php?title=Special:UserLogin&amp;returnto=Closure+%28computer+programming%29" title="You&#039;re encouraged to log in; however, it&#039;s not mandatory. [o]" accesskey="o"><span class="vector-icon mw-ui-icon-logIn mw-ui-icon-wikimedia-logIn"></span> <span>Log in</span></a></li> </ul> </div> </div> <div id="p-user-menu-anon-editor" class="vector-menu mw-portlet mw-portlet-user-menu-anon-editor" > <div class="vector-menu-heading"> Pages for logged out editors <a href="/wiki/Help:Introduction" aria-label="Learn more about editing"><span>learn more</span></a> </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="pt-anoncontribs" class="mw-list-item"><a href="/wiki/Special:MyContributions" title="A list of edits made from this IP address [y]" accesskey="y"><span>Contributions</span></a></li><li id="pt-anontalk" class="mw-list-item"><a href="/wiki/Special:MyTalk" title="Discussion about edits from this IP address [n]" accesskey="n"><span>Talk</span></a></li> </ul> </div> </div> </div> </div> </nav> </div> </header> </div> <div class="mw-page-container"> <div class="mw-page-container-inner"> <div class="vector-sitenotice-container"> <div id="siteNotice"><!-- CentralNotice --></div> </div> <div class="vector-column-start"> <div class="vector-main-menu-container"> <div id="mw-navigation"> <nav id="mw-panel" class="vector-main-menu-landmark" aria-label="Site"> <div id="vector-main-menu-pinned-container" class="vector-pinned-container"> </div> </nav> </div> </div> <div class="vector-sticky-pinned-container"> <nav id="mw-panel-toc" aria-label="Contents" data-event-name="ui.sidebar-toc" class="mw-table-of-contents-container vector-toc-landmark"> <div id="vector-toc-pinned-container" class="vector-pinned-container"> <div id="vector-toc" class="vector-toc vector-pinnable-element"> <div class="vector-pinnable-header vector-toc-pinnable-header vector-pinnable-header-pinned" data-feature-name="toc-pinned" data-pinnable-element-id="vector-toc" > <h2 class="vector-pinnable-header-label">Contents</h2> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-pin-button" data-event-name="pinnable-header.vector-toc.pin">move to sidebar</button> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-unpin-button" data-event-name="pinnable-header.vector-toc.unpin">hide</button> </div> <ul class="vector-toc-contents" id="mw-panel-toc-list"> <li id="toc-mw-content-text" class="vector-toc-list-item vector-toc-level-1"> <a href="#" class="vector-toc-link"> <div class="vector-toc-text">(Top)</div> </a> </li> <li id="toc-History_and_etymology" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#History_and_etymology"> <div class="vector-toc-text"> <span class="vector-toc-numb">1</span> <span>History and etymology</span> </div> </a> <ul id="toc-History_and_etymology-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Anonymous_functions" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#Anonymous_functions"> <div class="vector-toc-text"> <span class="vector-toc-numb">2</span> <span>Anonymous functions</span> </div> </a> <ul id="toc-Anonymous_functions-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Applications" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#Applications"> <div class="vector-toc-text"> <span class="vector-toc-numb">3</span> <span>Applications</span> </div> </a> <button aria-controls="toc-Applications-sublist" class="cdx-button cdx-button--weight-quiet cdx-button--icon-only vector-toc-toggle"> <span class="vector-icon mw-ui-icon-wikimedia-expand"></span> <span>Toggle Applications subsection</span> </button> <ul id="toc-Applications-sublist" class="vector-toc-list"> <li id="toc-First-class_functions" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#First-class_functions"> <div class="vector-toc-text"> <span class="vector-toc-numb">3.1</span> <span>First-class functions</span> </div> </a> <ul id="toc-First-class_functions-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-State_representation" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#State_representation"> <div class="vector-toc-text"> <span class="vector-toc-numb">3.2</span> <span>State representation</span> </div> </a> <ul id="toc-State_representation-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Other_uses" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Other_uses"> <div class="vector-toc-text"> <span class="vector-toc-numb">3.3</span> <span>Other uses</span> </div> </a> <ul id="toc-Other_uses-sublist" class="vector-toc-list"> </ul> </li> </ul> </li> <li id="toc-Implementation_and_theory" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#Implementation_and_theory"> <div class="vector-toc-text"> <span class="vector-toc-numb">4</span> <span>Implementation and theory</span> </div> </a> <ul id="toc-Implementation_and_theory-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Differences_in_semantics" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#Differences_in_semantics"> <div class="vector-toc-text"> <span class="vector-toc-numb">5</span> <span>Differences in semantics</span> </div> </a> <button aria-controls="toc-Differences_in_semantics-sublist" class="cdx-button cdx-button--weight-quiet cdx-button--icon-only vector-toc-toggle"> <span class="vector-icon mw-ui-icon-wikimedia-expand"></span> <span>Toggle Differences in semantics subsection</span> </button> <ul id="toc-Differences_in_semantics-sublist" class="vector-toc-list"> <li id="toc-Lexical_environment" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Lexical_environment"> <div class="vector-toc-text"> <span class="vector-toc-numb">5.1</span> <span>Lexical environment</span> </div> </a> <ul id="toc-Lexical_environment-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Example_1:_Reference_to_an_unbound_variable" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Example_1:_Reference_to_an_unbound_variable"> <div class="vector-toc-text"> <span class="vector-toc-numb">5.2</span> <span>Example 1: Reference to an unbound variable</span> </div> </a> <ul id="toc-Example_1:_Reference_to_an_unbound_variable-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Example_2:_Accidental_reference_to_a_bound_variable" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Example_2:_Accidental_reference_to_a_bound_variable"> <div class="vector-toc-text"> <span class="vector-toc-numb">5.3</span> <span>Example 2: Accidental reference to a bound variable</span> </div> </a> <ul id="toc-Example_2:_Accidental_reference_to_a_bound_variable-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Closure_leaving" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Closure_leaving"> <div class="vector-toc-text"> <span class="vector-toc-numb">5.4</span> <span>Closure leaving</span> </div> </a> <ul id="toc-Closure_leaving-sublist" class="vector-toc-list"> </ul> </li> </ul> </li> <li id="toc-Closure-like_constructs" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#Closure-like_constructs"> <div class="vector-toc-text"> <span class="vector-toc-numb">6</span> <span>Closure-like constructs</span> </div> </a> <button aria-controls="toc-Closure-like_constructs-sublist" class="cdx-button cdx-button--weight-quiet cdx-button--icon-only vector-toc-toggle"> <span class="vector-icon mw-ui-icon-wikimedia-expand"></span> <span>Toggle Closure-like constructs subsection</span> </button> <ul id="toc-Closure-like_constructs-sublist" class="vector-toc-list"> <li id="toc-Callbacks_(C)" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Callbacks_(C)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.1</span> <span>Callbacks (C)</span> </div> </a> <ul id="toc-Callbacks_(C)-sublist" class="vector-toc-list"> <li id="toc-Nested_function_and_function_pointer_(C)" class="vector-toc-list-item vector-toc-level-3"> <a class="vector-toc-link" href="#Nested_function_and_function_pointer_(C)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.1.1</span> <span>Nested function and function pointer (C)</span> </div> </a> <ul id="toc-Nested_function_and_function_pointer_(C)-sublist" class="vector-toc-list"> </ul> </li> </ul> </li> <li id="toc-Local_classes_and_lambda_functions_(Java)" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Local_classes_and_lambda_functions_(Java)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.2</span> <span>Local classes and lambda functions (Java)</span> </div> </a> <ul id="toc-Local_classes_and_lambda_functions_(Java)-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Blocks_(C,_C++,_Objective-C_2.0)" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Blocks_(C,_C++,_Objective-C_2.0)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.3</span> <span>Blocks (C, C++, Objective-C 2.0)</span> </div> </a> <ul id="toc-Blocks_(C,_C++,_Objective-C_2.0)-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Delegates_(C#,_VB.NET,_D)" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Delegates_(C#,_VB.NET,_D)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.4</span> <span>Delegates (C#, VB.NET, D)</span> </div> </a> <ul id="toc-Delegates_(C#,_VB.NET,_D)-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Function_objects_(C++)" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Function_objects_(C++)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.5</span> <span>Function objects (C++)</span> </div> </a> <ul id="toc-Function_objects_(C++)-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Inline_agents_(Eiffel)" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#Inline_agents_(Eiffel)"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.6</span> <span>Inline agents (Eiffel)</span> </div> </a> <ul id="toc-Inline_agents_(Eiffel)-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-C++Builder_closure_reserved_word" class="vector-toc-list-item vector-toc-level-2"> <a class="vector-toc-link" href="#C++Builder_closure_reserved_word"> <div class="vector-toc-text"> <span class="vector-toc-numb">6.7</span> <span>C++Builder __closure reserved word</span> </div> </a> <ul id="toc-C++Builder_closure_reserved_word-sublist" class="vector-toc-list"> </ul> </li> </ul> </li> <li id="toc-See_also" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#See_also"> <div class="vector-toc-text"> <span class="vector-toc-numb">7</span> <span>See also</span> </div> </a> <ul id="toc-See_also-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-Notes" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#Notes"> <div class="vector-toc-text"> <span class="vector-toc-numb">8</span> <span>Notes</span> </div> </a> <ul id="toc-Notes-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-References" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#References"> <div class="vector-toc-text"> <span class="vector-toc-numb">9</span> <span>References</span> </div> </a> <ul id="toc-References-sublist" class="vector-toc-list"> </ul> </li> <li id="toc-External_links" class="vector-toc-list-item vector-toc-level-1 vector-toc-list-item-expanded"> <a class="vector-toc-link" href="#External_links"> <div class="vector-toc-text"> <span class="vector-toc-numb">10</span> <span>External links</span> </div> </a> <ul id="toc-External_links-sublist" class="vector-toc-list"> </ul> </li> </ul> </div> </div> </nav> </div> </div> <div class="mw-content-container"> <main id="content" class="mw-body"> <header class="mw-body-header vector-page-titlebar"> <nav aria-label="Contents" class="vector-toc-landmark"> <div id="vector-page-titlebar-toc" class="vector-dropdown vector-page-titlebar-toc vector-button-flush-left" > <input type="checkbox" id="vector-page-titlebar-toc-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-vector-page-titlebar-toc" class="vector-dropdown-checkbox " aria-label="Toggle the table of contents" > <label id="vector-page-titlebar-toc-label" for="vector-page-titlebar-toc-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet cdx-button--icon-only " aria-hidden="true" ><span class="vector-icon mw-ui-icon-listBullet mw-ui-icon-wikimedia-listBullet"></span> <span class="vector-dropdown-label-text">Toggle the table of contents</span> </label> <div class="vector-dropdown-content"> <div id="vector-page-titlebar-toc-unpinned-container" class="vector-unpinned-container"> </div> </div> </div> </nav> <h1 id="firstHeading" class="firstHeading mw-first-heading"><span class="mw-page-title-main">Closure (computer programming)</span></h1> <div id="p-lang-btn" class="vector-dropdown mw-portlet mw-portlet-lang" > <input type="checkbox" id="p-lang-btn-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-p-lang-btn" class="vector-dropdown-checkbox mw-interlanguage-selector" aria-label="Go to an article in another language. Available in 23 languages" > <label id="p-lang-btn-label" for="p-lang-btn-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet cdx-button--action-progressive mw-portlet-lang-heading-23" aria-hidden="true" ><span class="vector-icon mw-ui-icon-language-progressive mw-ui-icon-wikimedia-language-progressive"></span> <span class="vector-dropdown-label-text">23 languages</span> </label> <div class="vector-dropdown-content"> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li class="interlanguage-link interwiki-bg mw-list-item"><a href="https://bg.wikipedia.org/wiki/%D0%97%D0%B0%D1%82%D0%B2%D0%B0%D1%80%D1%8F%D0%BD%D0%B5_(%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B8%D0%BA%D0%B0)" title="Затваряне (информатика) – Bulgarian" lang="bg" hreflang="bg" data-title="Затваряне (информатика)" data-language-autonym="Български" data-language-local-name="Bulgarian" class="interlanguage-link-target"><span>Български</span></a></li><li class="interlanguage-link interwiki-de mw-list-item"><a href="https://de.wikipedia.org/wiki/Closure_(Funktion)" title="Closure (Funktion) – German" lang="de" hreflang="de" data-title="Closure (Funktion)" data-language-autonym="Deutsch" data-language-local-name="German" class="interlanguage-link-target"><span>Deutsch</span></a></li><li class="interlanguage-link interwiki-et mw-list-item"><a href="https://et.wikipedia.org/wiki/Sulund_(informaatika)" title="Sulund (informaatika) – Estonian" lang="et" hreflang="et" data-title="Sulund (informaatika)" data-language-autonym="Eesti" data-language-local-name="Estonian" class="interlanguage-link-target"><span>Eesti</span></a></li><li class="interlanguage-link interwiki-el mw-list-item"><a href="https://el.wikipedia.org/wiki/%CE%9A%CE%BB%CE%B5%CE%AF%CF%83%CE%B9%CE%BC%CE%BF_(%CE%B5%CF%80%CE%B9%CF%83%CF%84%CE%AE%CE%BC%CE%B7_%CF%85%CF%80%CE%BF%CE%BB%CE%BF%CE%B3%CE%B9%CF%83%CF%84%CF%8E%CE%BD)" title="Κλείσιμο (επιστήμη υπολογιστών) – Greek" lang="el" hreflang="el" data-title="Κλείσιμο (επιστήμη υπολογιστών)" data-language-autonym="Ελληνικά" data-language-local-name="Greek" class="interlanguage-link-target"><span>Ελληνικά</span></a></li><li class="interlanguage-link interwiki-es mw-list-item"><a href="https://es.wikipedia.org/wiki/Clausura_(inform%C3%A1tica)" title="Clausura (informática) – Spanish" lang="es" hreflang="es" data-title="Clausura (informática)" data-language-autonym="Español" data-language-local-name="Spanish" class="interlanguage-link-target"><span>Español</span></a></li><li class="interlanguage-link interwiki-fa mw-list-item"><a href="https://fa.wikipedia.org/wiki/%D8%A8%D8%B3%D8%AA%D8%A7%D8%B1_(%D8%B9%D9%84%D9%88%D9%85_%D8%B1%D8%A7%DB%8C%D8%A7%D9%86%D9%87)" title="بستار (علوم رایانه) – Persian" lang="fa" hreflang="fa" data-title="بستار (علوم رایانه)" data-language-autonym="فارسی" data-language-local-name="Persian" class="interlanguage-link-target"><span>فارسی</span></a></li><li class="interlanguage-link interwiki-fr mw-list-item"><a href="https://fr.wikipedia.org/wiki/Fermeture_(informatique)" title="Fermeture (informatique) – French" lang="fr" hreflang="fr" data-title="Fermeture (informatique)" data-language-autonym="Français" data-language-local-name="French" class="interlanguage-link-target"><span>Français</span></a></li><li class="interlanguage-link interwiki-ko mw-list-item"><a href="https://ko.wikipedia.org/wiki/%ED%81%B4%EB%A1%9C%EC%A0%80_(%EC%BB%B4%ED%93%A8%ED%84%B0_%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D)" title="클로저 (컴퓨터 프로그래밍) – Korean" lang="ko" hreflang="ko" data-title="클로저 (컴퓨터 프로그래밍)" data-language-autonym="한국어" data-language-local-name="Korean" class="interlanguage-link-target"><span>한국어</span></a></li><li class="interlanguage-link interwiki-it mw-list-item"><a href="https://it.wikipedia.org/wiki/Chiusura_(informatica)" title="Chiusura (informatica) – Italian" lang="it" hreflang="it" data-title="Chiusura (informatica)" data-language-autonym="Italiano" data-language-local-name="Italian" class="interlanguage-link-target"><span>Italiano</span></a></li><li class="interlanguage-link interwiki-he mw-list-item"><a href="https://he.wikipedia.org/wiki/%D7%A1%D7%92%D7%95%D7%A8_(%D7%A9%D7%A4%D7%95%D7%AA_%D7%AA%D7%9B%D7%A0%D7%95%D7%AA)" title="סגור (שפות תכנות) – Hebrew" lang="he" hreflang="he" data-title="סגור (שפות תכנות)" data-language-autonym="עברית" data-language-local-name="Hebrew" class="interlanguage-link-target"><span>עברית</span></a></li><li class="interlanguage-link interwiki-nl mw-list-item"><a href="https://nl.wikipedia.org/wiki/Closure" title="Closure – Dutch" lang="nl" hreflang="nl" data-title="Closure" data-language-autonym="Nederlands" data-language-local-name="Dutch" class="interlanguage-link-target"><span>Nederlands</span></a></li><li class="interlanguage-link interwiki-ja mw-list-item"><a href="https://ja.wikipedia.org/wiki/%E3%82%AF%E3%83%AD%E3%83%BC%E3%82%B8%E3%83%A3" title="クロージャ – Japanese" lang="ja" hreflang="ja" data-title="クロージャ" data-language-autonym="日本語" data-language-local-name="Japanese" class="interlanguage-link-target"><span>日本語</span></a></li><li class="interlanguage-link interwiki-pl mw-list-item"><a href="https://pl.wikipedia.org/wiki/Domkni%C4%99cie_(programowanie)" title="Domknięcie (programowanie) – Polish" lang="pl" hreflang="pl" data-title="Domknięcie (programowanie)" data-language-autonym="Polski" data-language-local-name="Polish" class="interlanguage-link-target"><span>Polski</span></a></li><li class="interlanguage-link interwiki-pt mw-list-item"><a href="https://pt.wikipedia.org/wiki/Clausura_(ci%C3%AAncia_da_computa%C3%A7%C3%A3o)" title="Clausura (ciência da computação) – Portuguese" lang="pt" hreflang="pt" data-title="Clausura (ciência da computação)" data-language-autonym="Português" data-language-local-name="Portuguese" class="interlanguage-link-target"><span>Português</span></a></li><li class="interlanguage-link interwiki-ru mw-list-item"><a href="https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%BC%D1%8B%D0%BA%D0%B0%D0%BD%D0%B8%D0%B5_(%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5)" title="Замыкание (программирование) – Russian" lang="ru" hreflang="ru" data-title="Замыкание (программирование)" data-language-autonym="Русский" data-language-local-name="Russian" class="interlanguage-link-target"><span>Русский</span></a></li><li class="interlanguage-link interwiki-simple mw-list-item"><a href="https://simple.wikipedia.org/wiki/Closure_(computer_programming)" title="Closure (computer programming) – Simple English" lang="en-simple" hreflang="en-simple" data-title="Closure (computer programming)" data-language-autonym="Simple English" data-language-local-name="Simple English" class="interlanguage-link-target"><span>Simple English</span></a></li><li class="interlanguage-link interwiki-sr mw-list-item"><a href="https://sr.wikipedia.org/wiki/%D0%97%D0%B0%D1%82%D0%B2%D0%BE%D1%80%D0%B5%D1%9A%D0%B5_(%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%B8%D1%80%D0%B0%D1%9A%D0%B5)" title="Затворење (програмирање) – Serbian" lang="sr" hreflang="sr" data-title="Затворење (програмирање)" data-language-autonym="Српски / srpski" data-language-local-name="Serbian" class="interlanguage-link-target"><span>Српски / srpski</span></a></li><li class="interlanguage-link interwiki-fi mw-list-item"><a href="https://fi.wikipedia.org/wiki/Sulkeuma_(ohjelmointi)" title="Sulkeuma (ohjelmointi) – Finnish" lang="fi" hreflang="fi" data-title="Sulkeuma (ohjelmointi)" data-language-autonym="Suomi" data-language-local-name="Finnish" class="interlanguage-link-target"><span>Suomi</span></a></li><li class="interlanguage-link interwiki-ta mw-list-item"><a href="https://ta.wikipedia.org/wiki/%E0%AE%85%E0%AE%9F%E0%AF%88%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%81_(%E0%AE%95%E0%AE%A3%E0%AE%BF%E0%AE%A9%E0%AE%BF%E0%AE%AF%E0%AE%BF%E0%AE%AF%E0%AE%B2%E0%AF%8D)" title="அடைப்பு (கணினியியல்) – Tamil" lang="ta" hreflang="ta" data-title="அடைப்பு (கணினியியல்)" data-language-autonym="தமிழ்" data-language-local-name="Tamil" class="interlanguage-link-target"><span>தமிழ்</span></a></li><li class="interlanguage-link interwiki-th mw-list-item"><a href="https://th.wikipedia.org/wiki/%E0%B8%AA%E0%B9%88%E0%B8%A7%E0%B8%99%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B8%84%E0%B8%A5%E0%B8%B8%E0%B8%A1_(%E0%B8%A7%E0%B8%B4%E0%B8%97%E0%B8%A2%E0%B8%B2%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%84%E0%B8%AD%E0%B8%A1%E0%B8%9E%E0%B8%B4%E0%B8%A7%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C)" title="ส่วนปิดคลุม (วิทยาการคอมพิวเตอร์) – Thai" lang="th" hreflang="th" data-title="ส่วนปิดคลุม (วิทยาการคอมพิวเตอร์)" data-language-autonym="ไทย" data-language-local-name="Thai" class="interlanguage-link-target"><span>ไทย</span></a></li><li class="interlanguage-link interwiki-uk mw-list-item"><a href="https://uk.wikipedia.org/wiki/%D0%97%D0%B0%D0%BC%D0%B8%D0%BA%D0%B0%D0%BD%D0%BD%D1%8F_(%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D1%83%D0%B2%D0%B0%D0%BD%D0%BD%D1%8F)" title="Замикання (програмування) – Ukrainian" lang="uk" hreflang="uk" data-title="Замикання (програмування)" data-language-autonym="Українська" data-language-local-name="Ukrainian" class="interlanguage-link-target"><span>Українська</span></a></li><li class="interlanguage-link interwiki-vi mw-list-item"><a href="https://vi.wikipedia.org/wiki/Bao_%C4%91%C3%B3ng_(l%E1%BA%ADp_tr%C3%ACnh_m%C3%A1y_t%C3%ADnh)" title="Bao đóng (lập trình máy tính) – Vietnamese" lang="vi" hreflang="vi" data-title="Bao đóng (lập trình máy tính)" data-language-autonym="Tiếng Việt" data-language-local-name="Vietnamese" class="interlanguage-link-target"><span>Tiếng Việt</span></a></li><li class="interlanguage-link interwiki-zh mw-list-item"><a href="https://zh.wikipedia.org/wiki/%E9%97%AD%E5%8C%85_(%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A7%91%E5%AD%A6)" title="闭包 (计算机科学) – Chinese" lang="zh" hreflang="zh" data-title="闭包 (计算机科学)" data-language-autonym="中文" data-language-local-name="Chinese" class="interlanguage-link-target"><span>中文</span></a></li> </ul> <div class="after-portlet after-portlet-lang"><span class="wb-langlinks-edit wb-langlinks-link"><a href="https://www.wikidata.org/wiki/Special:EntityPage/Q535335#sitelinks-wikipedia" title="Edit interlanguage links" class="wbc-editpage">Edit links</a></span></div> </div> </div> </div> </header> <div class="vector-page-toolbar"> <div class="vector-page-toolbar-container"> <div id="left-navigation"> <nav aria-label="Namespaces"> <div id="p-associated-pages" class="vector-menu vector-menu-tabs mw-portlet mw-portlet-associated-pages" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="ca-nstab-main" class="selected vector-tab-noicon mw-list-item"><a href="/wiki/Closure_(computer_programming)" title="View the content page [c]" accesskey="c"><span>Article</span></a></li><li id="ca-talk" class="vector-tab-noicon mw-list-item"><a href="/wiki/Talk:Closure_(computer_programming)" rel="discussion" title="Discuss improvements to the content page [t]" accesskey="t"><span>Talk</span></a></li> </ul> </div> </div> <div id="vector-variants-dropdown" class="vector-dropdown emptyPortlet" > <input type="checkbox" id="vector-variants-dropdown-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-vector-variants-dropdown" class="vector-dropdown-checkbox " aria-label="Change language variant" > <label id="vector-variants-dropdown-label" for="vector-variants-dropdown-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet" aria-hidden="true" ><span class="vector-dropdown-label-text">English</span> </label> <div class="vector-dropdown-content"> <div id="p-variants" class="vector-menu mw-portlet mw-portlet-variants emptyPortlet" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> </ul> </div> </div> </div> </div> </nav> </div> <div id="right-navigation" class="vector-collapsible"> <nav aria-label="Views"> <div id="p-views" class="vector-menu vector-menu-tabs mw-portlet mw-portlet-views" > <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="ca-view" class="selected vector-tab-noicon mw-list-item"><a href="/wiki/Closure_(computer_programming)"><span>Read</span></a></li><li id="ca-edit" class="vector-tab-noicon mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit" title="Edit this page [e]" accesskey="e"><span>Edit</span></a></li><li id="ca-history" class="vector-tab-noicon mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=history" title="Past revisions of this page [h]" accesskey="h"><span>View history</span></a></li> </ul> </div> </div> </nav> <nav class="vector-page-tools-landmark" aria-label="Page tools"> <div id="vector-page-tools-dropdown" class="vector-dropdown vector-page-tools-dropdown" > <input type="checkbox" id="vector-page-tools-dropdown-checkbox" role="button" aria-haspopup="true" data-event-name="ui.dropdown-vector-page-tools-dropdown" class="vector-dropdown-checkbox " aria-label="Tools" > <label id="vector-page-tools-dropdown-label" for="vector-page-tools-dropdown-checkbox" class="vector-dropdown-label cdx-button cdx-button--fake-button cdx-button--fake-button--enabled cdx-button--weight-quiet" aria-hidden="true" ><span class="vector-dropdown-label-text">Tools</span> </label> <div class="vector-dropdown-content"> <div id="vector-page-tools-unpinned-container" class="vector-unpinned-container"> <div id="vector-page-tools" class="vector-page-tools vector-pinnable-element"> <div class="vector-pinnable-header vector-page-tools-pinnable-header vector-pinnable-header-unpinned" data-feature-name="page-tools-pinned" data-pinnable-element-id="vector-page-tools" data-pinned-container-id="vector-page-tools-pinned-container" data-unpinned-container-id="vector-page-tools-unpinned-container" > <div class="vector-pinnable-header-label">Tools</div> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-pin-button" data-event-name="pinnable-header.vector-page-tools.pin">move to sidebar</button> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-unpin-button" data-event-name="pinnable-header.vector-page-tools.unpin">hide</button> </div> <div id="p-cactions" class="vector-menu mw-portlet mw-portlet-cactions emptyPortlet vector-has-collapsible-items" title="More options" > <div class="vector-menu-heading"> Actions </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="ca-more-view" class="selected vector-more-collapsible-item mw-list-item"><a href="/wiki/Closure_(computer_programming)"><span>Read</span></a></li><li id="ca-more-edit" class="vector-more-collapsible-item mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit" title="Edit this page [e]" accesskey="e"><span>Edit</span></a></li><li id="ca-more-history" class="vector-more-collapsible-item mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=history"><span>View history</span></a></li> </ul> </div> </div> <div id="p-tb" class="vector-menu mw-portlet mw-portlet-tb" > <div class="vector-menu-heading"> General </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="t-whatlinkshere" class="mw-list-item"><a href="/wiki/Special:WhatLinksHere/Closure_(computer_programming)" title="List of all English Wikipedia pages containing links to this page [j]" accesskey="j"><span>What links here</span></a></li><li id="t-recentchangeslinked" class="mw-list-item"><a href="/wiki/Special:RecentChangesLinked/Closure_(computer_programming)" rel="nofollow" title="Recent changes in pages linked from this page [k]" accesskey="k"><span>Related changes</span></a></li><li id="t-upload" class="mw-list-item"><a href="/wiki/Wikipedia:File_Upload_Wizard" title="Upload files [u]" accesskey="u"><span>Upload file</span></a></li><li id="t-specialpages" class="mw-list-item"><a href="/wiki/Special:SpecialPages" title="A list of all special pages [q]" accesskey="q"><span>Special pages</span></a></li><li id="t-permalink" class="mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;oldid=1246240241" title="Permanent link to this revision of this page"><span>Permanent link</span></a></li><li id="t-info" class="mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=info" title="More information about this page"><span>Page information</span></a></li><li id="t-cite" class="mw-list-item"><a href="/w/index.php?title=Special:CiteThisPage&amp;page=Closure_%28computer_programming%29&amp;id=1246240241&amp;wpFormIdentifier=titleform" title="Information on how to cite this page"><span>Cite this page</span></a></li><li id="t-urlshortener" class="mw-list-item"><a href="/w/index.php?title=Special:UrlShortener&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FClosure_%28computer_programming%29"><span>Get shortened URL</span></a></li><li id="t-urlshortener-qrcode" class="mw-list-item"><a href="/w/index.php?title=Special:QrCode&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FClosure_%28computer_programming%29"><span>Download QR code</span></a></li> </ul> </div> </div> <div id="p-coll-print_export" class="vector-menu mw-portlet mw-portlet-coll-print_export" > <div class="vector-menu-heading"> Print/export </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="coll-download-as-rl" class="mw-list-item"><a href="/w/index.php?title=Special:DownloadAsPdf&amp;page=Closure_%28computer_programming%29&amp;action=show-download-screen" title="Download this page as a PDF file"><span>Download as PDF</span></a></li><li id="t-print" class="mw-list-item"><a href="/w/index.php?title=Closure_(computer_programming)&amp;printable=yes" title="Printable version of this page [p]" accesskey="p"><span>Printable version</span></a></li> </ul> </div> </div> <div id="p-wikibase-otherprojects" class="vector-menu mw-portlet mw-portlet-wikibase-otherprojects" > <div class="vector-menu-heading"> In other projects </div> <div class="vector-menu-content"> <ul class="vector-menu-content-list"> <li id="t-wikibase" class="wb-otherproject-link wb-otherproject-wikibase-dataitem mw-list-item"><a href="https://www.wikidata.org/wiki/Special:EntityPage/Q535335" title="Structured data on this page hosted by Wikidata [g]" accesskey="g"><span>Wikidata item</span></a></li> </ul> </div> </div> </div> </div> </div> </div> </nav> </div> </div> </div> <div class="vector-column-end"> <div class="vector-sticky-pinned-container"> <nav class="vector-page-tools-landmark" aria-label="Page tools"> <div id="vector-page-tools-pinned-container" class="vector-pinned-container"> </div> </nav> <nav class="vector-appearance-landmark" aria-label="Appearance"> <div id="vector-appearance-pinned-container" class="vector-pinned-container"> <div id="vector-appearance" class="vector-appearance vector-pinnable-element"> <div class="vector-pinnable-header vector-appearance-pinnable-header vector-pinnable-header-pinned" data-feature-name="appearance-pinned" data-pinnable-element-id="vector-appearance" data-pinned-container-id="vector-appearance-pinned-container" data-unpinned-container-id="vector-appearance-unpinned-container" > <div class="vector-pinnable-header-label">Appearance</div> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-pin-button" data-event-name="pinnable-header.vector-appearance.pin">move to sidebar</button> <button class="vector-pinnable-header-toggle-button vector-pinnable-header-unpin-button" data-event-name="pinnable-header.vector-appearance.unpin">hide</button> </div> </div> </div> </nav> </div> </div> <div id="bodyContent" class="vector-body" aria-labelledby="firstHeading" data-mw-ve-target-container> <div class="vector-body-before-content"> <div class="mw-indicators"> </div> <div id="siteSub" class="noprint">From Wikipedia, the free encyclopedia</div> </div> <div id="contentSub"><div id="mw-content-subtitle"><span class="mw-redirectedfrom">(Redirected from <a href="/w/index.php?title=Closure_(computer_science)&amp;redirect=no" class="mw-redirect" title="Closure (computer science)">Closure (computer science)</a>)</span></div></div> <div id="mw-content-text" class="mw-body-content"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr"><div class="shortdescription nomobile noexcerpt noprint searchaux" style="display:none">Technique for creating lexically scoped first class functions</div> <style data-mw-deduplicate="TemplateStyles:r1236090951">.mw-parser-output .hatnote{font-style:italic}.mw-parser-output div.hatnote{padding-left:1.6em;margin-bottom:0.5em}.mw-parser-output .hatnote i{font-style:normal}.mw-parser-output .hatnote+link+.hatnote{margin-top:-0.5em}@media print{body.ns-0 .mw-parser-output .hatnote{display:none!important}}</style><div role="note" class="hatnote navigation-not-searchable">For other uses, see <a href="/wiki/Closure_(mathematics)" title="Closure (mathematics)">Closure (mathematics)</a> and <a href="/wiki/Closure_(disambiguation)" class="mw-redirect mw-disambig" title="Closure (disambiguation)">Closure (disambiguation)</a>.</div> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1236090951"><div role="note" class="hatnote navigation-not-searchable">Not to be confused with the programming language <a href="/wiki/Clojure" title="Clojure">Clojure</a>.</div> <p> In <a href="/wiki/Programming_language" title="Programming language">programming languages</a>, a <b>closure</b>, also <b>lexical closure</b> or <b>function closure</b>, is a technique for implementing <a href="/wiki/Lexically_scoped" class="mw-redirect" title="Lexically scoped">lexically scoped</a> <a href="/wiki/Name_binding" title="Name binding">name binding</a> in a language with <a href="/wiki/First-class_function" title="First-class function">first-class functions</a>. <a href="/wiki/Operational_semantics" title="Operational semantics">Operationally</a>, a closure is a <a href="/wiki/Record_(computer_science)" title="Record (computer science)">record</a> storing a <a href="/wiki/Function_(computer_science)" class="mw-redirect" title="Function (computer science)">function</a><sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">&#91;</span>a<span class="cite-bracket">&#93;</span></a></sup> together with an environment.<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">&#91;</span>1<span class="cite-bracket">&#93;</span></a></sup> The environment is a mapping associating each <a href="/wiki/Free_variable" class="mw-redirect" title="Free variable">free variable</a> of the function (variables that are used locally, but defined in an enclosing scope) with the <a href="/wiki/Value_(computer_science)" title="Value (computer science)">value</a> or <a href="/wiki/Reference_(computer_science)" title="Reference (computer science)">reference</a> to which the name was bound when the closure was created.<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span class="cite-bracket">&#91;</span>b<span class="cite-bracket">&#93;</span></a></sup> Unlike a plain function, a closure allows the function to access those <i>captured variables</i> through the closure's copies of their values or references, even when the function is invoked outside their scope. </p> <meta property="mw:PageProp/toc" /> <div class="mw-heading mw-heading2"><h2 id="History_and_etymology">History and etymology</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=1" title="Edit section: History and etymology"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>The concept of closures was developed in the 1960s for the mechanical evaluation of expressions in the <a href="/wiki/%CE%9B-calculus" class="mw-redirect" title="Λ-calculus">λ-calculus</a> and was first fully implemented in 1970 as a language feature in the <a href="/wiki/PAL_(programming_language)" title="PAL (programming language)">PAL programming language</a> to support lexically scoped <a href="/wiki/First-class_function" title="First-class function">first-class functions</a>.<sup id="cite_ref-dat2012_4-0" class="reference"><a href="#cite_note-dat2012-4"><span class="cite-bracket">&#91;</span>2<span class="cite-bracket">&#93;</span></a></sup> </p><p><a href="/wiki/Peter_Landin" title="Peter Landin">Peter Landin</a> defined the term <i>closure</i> in 1964 as having an <i>environment part</i> and a <i>control part</i> as used by his <a href="/wiki/SECD_machine" title="SECD machine">SECD machine</a> for evaluating expressions.<sup id="cite_ref-landin_5-0" class="reference"><a href="#cite_note-landin-5"><span class="cite-bracket">&#91;</span>3<span class="cite-bracket">&#93;</span></a></sup> <a href="/wiki/Joel_Moses" title="Joel Moses">Joel Moses</a> credits Landin with introducing the term <i>closure</i> to refer to a <a href="/wiki/Anonymous_function" title="Anonymous function">lambda expression</a> with open bindings (free variables) that have been closed by (or bound in) the lexical environment, resulting in a <i>closed expression</i>, or closure.<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span class="cite-bracket">&#91;</span>4<span class="cite-bracket">&#93;</span></a></sup><sup id="cite_ref-7" class="reference"><a href="#cite_note-7"><span class="cite-bracket">&#91;</span>5<span class="cite-bracket">&#93;</span></a></sup> This use was subsequently adopted by <a href="/wiki/Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman</a> and <a href="/wiki/Guy_L._Steele_Jr." title="Guy L. Steele Jr.">Steele</a> when they defined <a href="/wiki/Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a> in 1975,<sup id="cite_ref-8" class="reference"><a href="#cite_note-8"><span class="cite-bracket">&#91;</span>6<span class="cite-bracket">&#93;</span></a></sup> a lexically scoped variant of <a href="/wiki/Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a>, and became widespread. </p><p>Sussman and <a href="/wiki/Harold_Abelson" class="mw-redirect" title="Harold Abelson">Abelson</a> also use the term <i>closure</i> in the 1980s with a second, unrelated meaning: the property of an operator that adds data to a <a href="/wiki/Data_structure" title="Data structure">data structure</a> to also be able to add nested data structures. This use of the term comes from <a href="/wiki/Closure_(mathematics)" title="Closure (mathematics)">mathematics use</a>, rather than the prior use in computer science. The authors consider this overlap in terminology to be "unfortunate."<sup id="cite_ref-9" class="reference"><a href="#cite_note-9"><span class="cite-bracket">&#91;</span>7<span class="cite-bracket">&#93;</span></a></sup> </p> <div class="mw-heading mw-heading2"><h2 id="Anonymous_functions">Anonymous functions</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=2" title="Edit section: Anonymous functions"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1236090951"><div role="note" class="hatnote navigation-not-searchable">Further information: <a href="/wiki/Anonymous_function" title="Anonymous function">Anonymous function</a></div> <p>The term <i>closure</i> is often used as a synonym for <a href="/wiki/Anonymous_function" title="Anonymous function">anonymous function</a>, though strictly, an anonymous function is a function <a href="/wiki/Literal_(computer_programming)" title="Literal (computer programming)">literal</a> without a name, while a closure is an instance of a function, a <a href="/wiki/Value_(computer_science)" title="Value (computer science)">value</a>, whose non-local variables have been bound either to values or to <a href="/wiki/Variable_(computer_science)" title="Variable (computer science)">storage locations</a> (depending on the language; see the <a href="#Lexical_environment">lexical environment</a> section below). </p><p>For example, in the following <a href="/wiki/Python_(programming_language)" title="Python (programming language)">Python</a> code: </p> <div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="k">return</span> <span class="n">g</span> <span class="c1"># Return a closure.</span> <span class="k">def</span> <span class="nf">h</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="k">return</span> <span class="k">lambda</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="c1"># Return a closure.</span> <span class="c1"># Assigning specific closures to variables.</span> <span class="n">a</span> <span class="o">=</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">b</span> <span class="o">=</span> <span class="n">h</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># Using the closures stored in variables.</span> <span class="k">assert</span> <span class="n">a</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span> <span class="k">assert</span> <span class="n">b</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span> <span class="c1"># Using closures without binding them to variables first.</span> <span class="k">assert</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span> <span class="c1"># f(1) is the closure.</span> <span class="k">assert</span> <span class="n">h</span><span class="p">(</span><span class="mi">1</span><span class="p">)(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span> <span class="c1"># h(1) is the closure.</span> </pre></div> <p>the values of <code>a</code> and <code>b</code> are closures, in both cases produced by returning a <a href="/wiki/Nested_function" title="Nested function">nested function</a> with a free variable from the enclosing function, so that the free variable binds to the value of parameter <code>x</code> of the enclosing function. The closures in <code>a</code> and <code>b</code> are functionally identical. The only difference in implementation is that in the first case we used a nested function with a name, <code>g</code>, while in the second case we used an anonymous nested function (using the Python keyword <code>lambda</code> for creating an anonymous function). The original name, if any, used in defining them is irrelevant. </p><p>A closure is a value like any other value. It does not need to be assigned to a variable and can instead be used directly, as shown in the last two lines of the example. This usage may be deemed an "anonymous closure". </p><p>The nested function definitions are not themselves closures: they have a free variable which is not yet bound. Only once the enclosing function is evaluated with a value for the parameter is the free variable of the nested function bound, creating a closure, which is then returned from the enclosing function. </p><p>Lastly, a closure is only distinct from a function with free variables when outside of the scope of the non-local variables, otherwise the defining environment and the execution environment coincide and there is nothing to distinguish these (static and dynamic binding cannot be distinguished because the names resolve to the same values). For example, in the program below, functions with a free variable <code>x</code> (bound to the non-local variable <code>x</code> with global scope) are executed in the same environment where <code>x</code> is defined, so it is immaterial whether these are actually closures: </p> <div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="n">nums</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">nums</span><span class="p">)</span> <span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span><span class="p">,</span> <span class="n">nums</span><span class="p">)</span> </pre></div> <p>This is most often achieved by a function return, since the function must be defined within the scope of the non-local variables, in which case typically its own scope will be smaller. </p><p>This can also be achieved by <a href="/wiki/Variable_shadowing" title="Variable shadowing">variable shadowing</a> (which reduces the scope of the non-local variable), though this is less common in practice, as it is less useful and shadowing is discouraged. In this example <code>f</code> can be seen to be a closure because <code>x</code> in the body of <code>f</code> is bound to the <code>x</code> in the global namespace, not the <code>x</code> local to <code>g</code>: </p> <div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">z</span><span class="p">):</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># local x shadows global x</span> <span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="n">z</span><span class="p">)</span> <span class="n">g</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># evaluates to 1, not 2</span> </pre></div> <div class="mw-heading mw-heading2"><h2 id="Applications">Applications</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=3" title="Edit section: Applications"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>The use of closures is associated with languages where functions are <a href="/wiki/First-class_object" class="mw-redirect" title="First-class object">first-class objects</a>, in which functions can be returned as results from <a href="/wiki/Higher-order_function" title="Higher-order function">higher-order functions</a>, or passed as arguments to other function calls; if functions with free variables are first-class, then returning one creates a closure. This includes <a href="/wiki/Functional_programming" title="Functional programming">functional programming</a> languages such as <a href="/wiki/Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a> and <a href="/wiki/ML_(programming_language)" title="ML (programming language)">ML</a>, and many modern, multi-paradigm languages, such as <a href="/wiki/Julia_(programming_language)" title="Julia (programming language)">Julia</a>, <a href="/wiki/Python_(programming_language)" title="Python (programming language)">Python</a>, and <a href="/wiki/Rust_(programming_language)" title="Rust (programming language)">Rust</a>. Closures are also often used with <a href="/wiki/Callback_(computer_programming)" title="Callback (computer programming)">callbacks</a>, particularly for <a href="/wiki/Event_handler" class="mw-redirect" title="Event handler">event handlers</a>, such as in <a href="/wiki/JavaScript" title="JavaScript">JavaScript</a>, where they are used for interactions with a <a href="/wiki/Dynamic_web_page" title="Dynamic web page">dynamic web page</a>. </p><p>Closures can also be used in a <a href="/wiki/Continuation-passing_style" title="Continuation-passing style">continuation-passing style</a> to <a href="/wiki/Information_hiding" title="Information hiding">hide state</a>. Constructs such as <a href="/wiki/Object_(computer_science)" title="Object (computer science)">objects</a> and <a href="/wiki/Control_structure" class="mw-redirect" title="Control structure">control structures</a> can thus be implemented with closures. In some languages, a closure may occur when a function is defined within another function, and the inner function refers to local variables of the outer function. At <a href="/wiki/Run_time_(program_lifecycle_phase)" class="mw-redirect" title="Run time (program lifecycle phase)">run-time</a>, when the outer function executes, a closure is formed, consisting of the inner function's code and references (the upvalues) to any variables of the outer function required by the closure. </p> <div class="mw-heading mw-heading3"><h3 id="First-class_functions">First-class functions</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=4" title="Edit section: First-class functions"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1236090951"><div role="note" class="hatnote navigation-not-searchable">Further information: <a href="/wiki/First-class_function" title="First-class function">First-class function</a></div> <p>Closures typically appear in languages with <a href="/wiki/First-class_object" class="mw-redirect" title="First-class object">first-class functions</a>—in other words, such languages enable functions to be passed as arguments, returned from function calls, bound to variable names, etc., just like simpler types such as strings and integers. For example, consider the following <a href="/wiki/Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a> function: </p> <div class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">; Return a list of all books with at least THRESHOLD copies sold.</span> <span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">best-selling-books</span><span class="w"> </span><span class="nv">threshold</span><span class="p">)</span> <span class="w"> </span><span class="p">(</span><span class="nb">filter</span> <span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">book</span><span class="p">)</span> <span class="w"> </span><span class="p">(</span><span class="nb">&gt;=</span><span class="w"> </span><span class="p">(</span><span class="nf">book-sales</span><span class="w"> </span><span class="nv">book</span><span class="p">)</span><span class="w"> </span><span class="nv">threshold</span><span class="p">))</span> <span class="w"> </span><span class="nv">book-list</span><span class="p">))</span> </pre></div> <p>In this example, the <a href="/wiki/Lambda_(programming)" class="mw-redirect" title="Lambda (programming)">lambda expression</a> <code>(lambda (book) (&gt;= (book-sales book) threshold))</code> appears within the function <code>best-selling-books</code>. When the lambda expression is evaluated, Scheme creates a closure consisting of the code for the lambda expression and a reference to the <code>threshold</code> variable, which is a <a href="/wiki/Free_variable" class="mw-redirect" title="Free variable">free variable</a> inside the lambda expression. </p><p>The closure is then passed to the <code>filter</code> function, which calls it repeatedly to determine which books are to be added to the result list and which are to be discarded. Because the closure has a reference to <code>threshold</code>, it can use that variable each time <code>filter</code> calls it. The function <code>filter</code> might be defined in a separate file. </p><p>Here is the same example rewritten in <a href="/wiki/JavaScript" title="JavaScript">JavaScript</a>, another popular language with support for closures: </p> <div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">// Return a list of all books with at least &#39;threshold&#39; copies sold.</span> <span class="kd">function</span><span class="w"> </span><span class="nx">bestSellingBooks</span><span class="p">(</span><span class="nx">threshold</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">bookList</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="nx">book</span><span class="w"> </span><span class="p">=&gt;</span><span class="w"> </span><span class="nx">book</span><span class="p">.</span><span class="nx">sales</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="nx">threshold</span><span class="p">);</span> <span class="p">}</span> </pre></div> <p>The arrow operator <code>=&gt;</code> is used to define an <a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow%20functions">arrow function expression</a>, and an <code>Array.filter</code> method<sup id="cite_ref-10" class="reference"><a href="#cite_note-10"><span class="cite-bracket">&#91;</span>8<span class="cite-bracket">&#93;</span></a></sup> instead of a global <code>filter</code> function, but otherwise the structure and the effect of the code are the same. </p><p>A function may create a closure and return it, as in this example: </p> <div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">// Return a function that approximates the derivative of f</span> <span class="c1">// using an interval of dx, which should be appropriately small.</span> <span class="kd">function</span><span class="w"> </span><span class="nx">derivative</span><span class="p">(</span><span class="nx">f</span><span class="p">,</span><span class="w"> </span><span class="nx">dx</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="w"> </span><span class="p">=&gt;</span><span class="w"> </span><span class="p">(</span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">dx</span><span class="p">)</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="nx">dx</span><span class="p">;</span> <span class="p">}</span> </pre></div> <p>Because the closure in this case outlives the execution of the function that creates it, the variables <code>f</code> and <code>dx</code> live on after the function <code>derivative</code> returns, even though execution has left their scope and they are no longer visible. In languages without closures, the lifetime of an automatic local variable coincides with the execution of the stack frame where that variable is declared. In languages with closures, variables must continue to exist as long as any existing closures have references to them. This is most commonly implemented using some form of <a href="/wiki/Garbage_collection_(computer_science)" title="Garbage collection (computer science)">garbage collection</a>. </p> <div class="mw-heading mw-heading3"><h3 id="State_representation">State representation</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=5" title="Edit section: State representation"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>A closure can be used to associate a function with a set of "<a href="/wiki/Class_(computer_programming)" title="Class (computer programming)">private</a>" variables, which persist over several invocations of the function. The <a href="/wiki/Scope_(programming)" class="mw-redirect" title="Scope (programming)">scope</a> of the variable encompasses only the closed-over function, so it cannot be accessed from other program code. These are analogous to <a href="/wiki/Private_variable" class="mw-redirect" title="Private variable">private variables</a> in <a href="/wiki/Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a>, and in fact closures are similar to stateful <a href="/wiki/Function_objects" class="mw-redirect" title="Function objects">function objects</a> (or functors) with a single call-operator method. </p><p>In stateful languages, closures can thus be used to implement paradigms for state representation and <a href="/wiki/Information_hiding" title="Information hiding">information hiding</a>, since the closure's upvalues (its closed-over variables) are of indefinite <a href="/wiki/Variable_(programming)#Scope_and_extent" class="mw-redirect" title="Variable (programming)">extent</a>, so a value established in one invocation remains available in the next. Closures used in this way no longer have <a href="/wiki/Referential_transparency" title="Referential transparency">referential transparency</a>, and are thus no longer <a href="/wiki/Pure_function" title="Pure function">pure functions</a>; nevertheless, they are commonly used in impure functional languages such as <a href="/wiki/Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>. </p> <div class="mw-heading mw-heading3"><h3 id="Other_uses">Other uses</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=6" title="Edit section: Other uses"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>Closures have many uses: </p> <ul><li>Because closures delay evaluation—i.e., they do not "do" anything until they are called—they can be used to define control structures. For example, all of <a href="/wiki/Smalltalk" title="Smalltalk">Smalltalk</a>'s standard control structures, including branches (if/then/else) and loops (while and for), are defined using objects whose methods accept closures. Users can easily define their own control structures also.</li> <li>In languages which implement assignment, multiple functions can be produced that close over the same environment, enabling them to communicate privately by altering that environment. In Scheme:</li></ul> <div class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" dir="ltr"><pre><span></span><span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="nv">foo</span><span class="w"> </span><span class="no">#f</span><span class="p">)</span> <span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="nv">bar</span><span class="w"> </span><span class="no">#f</span><span class="p">)</span> <span class="p">(</span><span class="k">let</span><span class="w"> </span><span class="p">((</span><span class="nf">secret-message</span><span class="w"> </span><span class="s">&quot;none&quot;</span><span class="p">))</span> <span class="w"> </span><span class="p">(</span><span class="k">set!</span><span class="w"> </span><span class="nv">foo</span><span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">msg</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="k">set!</span><span class="w"> </span><span class="nv">secret-message</span><span class="w"> </span><span class="nv">msg</span><span class="p">)))</span> <span class="w"> </span><span class="p">(</span><span class="k">set!</span><span class="w"> </span><span class="nv">bar</span><span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">()</span><span class="w"> </span><span class="nv">secret-message</span><span class="p">)))</span> <span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints &quot;none&quot;</span> <span class="p">(</span><span class="nb">newline</span><span class="p">)</span> <span class="p">(</span><span class="nf">foo</span><span class="w"> </span><span class="s">&quot;meet me by the docks at midnight&quot;</span><span class="p">)</span> <span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints &quot;meet me by the docks at midnight&quot;</span> </pre></div> <ul><li>Closures can be used to implement <a href="/wiki/Object-oriented_programming" title="Object-oriented programming">object</a> systems.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11"><span class="cite-bracket">&#91;</span>9<span class="cite-bracket">&#93;</span></a></sup></li></ul> <p>Note: Some speakers call any data structure that binds a <a href="/wiki/Scope_(programming)#Lexical_scoping" class="mw-redirect" title="Scope (programming)">lexical</a> environment a closure, but the term usually refers specifically to functions. </p> <div class="mw-heading mw-heading2"><h2 id="Implementation_and_theory">Implementation and theory</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=7" title="Edit section: Implementation and theory"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>Closures are typically implemented with a special <a href="/wiki/Data_structure" title="Data structure">data structure</a> that contains a <a href="/wiki/Function_pointer" title="Function pointer">pointer to the function code</a>, plus a representation of the function's lexical environment (i.e., the set of available variables) at the time when the closure was created. The referencing environment <a href="/wiki/Name_binding" title="Name binding">binds</a> the non-local names to the corresponding variables in the lexical environment at the time the closure is created, additionally extending their lifetime to at least as long as the lifetime of the closure. When the closure is entered at a later time, possibly with a different lexical environment, the function is executed with its non-local variables referring to the ones captured by the closure, not the current environment. </p><p>A language implementation cannot easily support full closures if its run-time memory model allocates all <a href="/wiki/Automatic_variable" title="Automatic variable">automatic variables</a> on a linear <a href="/wiki/Stack-based_memory_allocation" title="Stack-based memory allocation">stack</a>. In such languages, a function's automatic local variables are deallocated when the function returns. However, a closure requires that the free variables it references survive the enclosing function's execution. Therefore, those variables must be allocated so that they persist until no longer needed, typically via <a href="/wiki/Heap_allocation" class="mw-redirect" title="Heap allocation">heap allocation</a>, rather than on the stack, and their lifetime must be managed so they survive until all closures referencing them are no longer in use. </p><p>This explains why, typically, languages that natively support closures also use <a href="/wiki/Garbage_collection_(computer_science)" title="Garbage collection (computer science)">garbage collection</a>. The alternatives are manual memory management of non-local variables (explicitly allocating on the heap and freeing when done), or, if using stack allocation, for the language to accept that certain use cases will lead to <a href="/wiki/Undefined_behaviour" class="mw-redirect" title="Undefined behaviour">undefined behaviour</a>, due to <a href="/wiki/Dangling_pointer" title="Dangling pointer">dangling pointers</a> to freed automatic variables, as in lambda expressions in C++11<sup id="cite_ref-12" class="reference"><a href="#cite_note-12"><span class="cite-bracket">&#91;</span>10<span class="cite-bracket">&#93;</span></a></sup> or nested functions in GNU C.<sup id="cite_ref-13" class="reference"><a href="#cite_note-13"><span class="cite-bracket">&#91;</span>11<span class="cite-bracket">&#93;</span></a></sup> The <a href="/wiki/Funarg_problem" title="Funarg problem">funarg problem</a> (or "functional argument" problem) describes the difficulty of implementing functions as first class objects in a stack-based programming language such as C or C++. Similarly in <a href="/wiki/D_(programming_language)" title="D (programming language)">D</a> version 1, it is assumed that the programmer knows what to do with <a href="/wiki/Delegation_(programming)" class="mw-redirect" title="Delegation (programming)">delegates</a> and automatic local variables, as their references will be invalid after return from its definition scope (automatic local variables are on the stack) – this still permits many useful functional patterns, but for complex cases needs explicit <a href="/wiki/Heap_allocation" class="mw-redirect" title="Heap allocation">heap allocation</a> for variables. D version 2 solved this by detecting which variables must be stored on the heap, and performs automatic allocation. Because D uses garbage collection, in both versions, there is no need to track usage of variables as they are passed. </p><p>In strict functional languages with immutable data (<i>e.g.</i> <a href="/wiki/Erlang_(programming_language)" title="Erlang (programming language)">Erlang</a>), it is very easy to implement automatic memory management (garbage collection), as there are no possible cycles in variables' references. For example, in Erlang, all arguments and variables are allocated on the heap, but references to them are additionally stored on the stack. After a function returns, references are still valid. Heap cleaning is done by incremental garbage collector. </p><p>In ML, local variables are lexically scoped, and hence define a stack-like model, but since they are bound to values and not to objects, an implementation is free to copy these values into the closure's data structure in a way that is invisible to the programmer. </p><p><a href="/wiki/Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>, which has an <a href="/wiki/ALGOL" title="ALGOL">ALGOL</a>-like lexical scope system with dynamic variables and garbage collection, lacks a stack programming model and does not suffer from the limitations of stack-based languages. Closures are expressed naturally in Scheme. The lambda form encloses the code, and the free variables of its environment persist within the program as long as they can possibly be accessed, and so they can be used as freely as any other Scheme expression.<sup class="noprint Inline-Template Template-Fact" style="white-space:nowrap;">&#91;<i><a href="/wiki/Wikipedia:Citation_needed" title="Wikipedia:Citation needed"><span title="This claim needs references to reliable sources. (December 2014)">citation needed</span></a></i>&#93;</sup> </p><p>Closures are closely related to Actors in the <a href="/wiki/Actor_model" title="Actor model">Actor model</a> of concurrent computation where the values in the function's lexical environment are called <i>acquaintances</i>. An important issue for closures in <a href="/wiki/Concurrent_programming" class="mw-redirect" title="Concurrent programming">concurrent programming</a> languages is whether the variables in a closure can be updated and, if so, how these updates can be synchronized. Actors provide one solution.<sup id="cite_ref-14" class="reference"><a href="#cite_note-14"><span class="cite-bracket">&#91;</span>12<span class="cite-bracket">&#93;</span></a></sup> </p><p>Closures are closely related to <a href="/wiki/Function_object" title="Function object">function objects</a>; the transformation from the former to the latter is known as <a href="/wiki/Defunctionalization" title="Defunctionalization">defunctionalization</a> or <a href="/wiki/Lambda_lifting" title="Lambda lifting">lambda lifting</a>; see also <a href="/wiki/Closure_conversion" class="mw-redirect" title="Closure conversion">closure conversion</a>.<sup class="noprint Inline-Template Template-Fact" style="white-space:nowrap;">&#91;<i><a href="/wiki/Wikipedia:Citation_needed" title="Wikipedia:Citation needed"><span title="This claim needs references to reliable sources. (September 2011)">citation needed</span></a></i>&#93;</sup> </p> <div class="mw-heading mw-heading2"><h2 id="Differences_in_semantics">Differences in semantics</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=8" title="Edit section: Differences in semantics"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <div class="mw-heading mw-heading3"><h3 id="Lexical_environment">Lexical environment</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=9" title="Edit section: Lexical environment"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>As different languages do not always have a common definition of the lexical environment, their definitions of closure may vary also. The commonly held minimalist definition of the lexical environment defines it as a set of all <a href="/wiki/Name_binding" title="Name binding">bindings of variables</a> in the scope, and that is also what closures in any language have to capture. However the meaning of a <a href="/wiki/Variable_(programming)" class="mw-redirect" title="Variable (programming)">variable</a> binding also differs. In imperative languages, variables bind to relative locations in memory that can store values. Although the relative location of a binding does not change at runtime, the value in the bound location can. In such languages, since closure captures the binding, any operation on the variable, whether done from the closure or not, are performed on the same relative memory location. This is often called capturing the variable "by reference". Here is an example illustrating the concept in <a href="/wiki/ECMAScript" title="ECMAScript">ECMAScript</a>, which is one such language: </p> <div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">// Javascript</span> <span class="kd">var</span><span class="w"> </span><span class="nx">f</span><span class="p">,</span><span class="w"> </span><span class="nx">g</span><span class="p">;</span> <span class="kd">function</span><span class="w"> </span><span class="nx">foo</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">x</span><span class="p">;</span> <span class="w"> </span><span class="nx">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">++</span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">};</span> <span class="w"> </span><span class="nx">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">--</span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">};</span> <span class="w"> </span><span class="nx">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">1</span><span class="p">;</span> <span class="w"> </span><span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;inside foo, call to f(): &#39;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">f</span><span class="p">());</span> <span class="p">}</span> <span class="nx">foo</span><span class="p">();</span><span class="w"> </span><span class="c1">// 2</span> <span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;call to g(): &#39;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">g</span><span class="p">());</span><span class="w"> </span><span class="c1">// 1 (--x)</span> <span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;call to g(): &#39;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">g</span><span class="p">());</span><span class="w"> </span><span class="c1">// 0 (--x)</span> <span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;call to f(): &#39;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">f</span><span class="p">());</span><span class="w"> </span><span class="c1">// 1 (++x)</span> <span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;call to f(): &#39;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">f</span><span class="p">());</span><span class="w"> </span><span class="c1">// 2 (++x)</span> </pre></div> <p>Function <code>foo</code> and the closures referred to by variables <code>f</code> and <code>g</code> all use the same relative memory location signified by local variable <code>x</code>. </p><p>In some instances the above behaviour may be undesirable, and it is necessary to bind a different lexical closure. Again in ECMAScript, this would be done using the <code>Function.bind()</code>. </p> <div class="mw-heading mw-heading3"><h3 id="Example_1:_Reference_to_an_unbound_variable">Example 1: Reference to an unbound variable</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=10" title="Edit section: Example 1: Reference to an unbound variable"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p><sup id="cite_ref-15" class="reference"><a href="#cite_note-15"><span class="cite-bracket">&#91;</span>13<span class="cite-bracket">&#93;</span></a></sup> </p> <div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="kd">var</span><span class="w"> </span><span class="nx">module</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="nx">x</span><span class="o">:</span><span class="w"> </span><span class="mf">42</span><span class="p">,</span> <span class="w"> </span><span class="nx">getX</span><span class="o">:</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="k">return</span><span class="w"> </span><span class="k">this</span><span class="p">.</span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">}</span> <span class="p">}</span> <span class="kd">var</span><span class="w"> </span><span class="nx">unboundGetX</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">module</span><span class="p">.</span><span class="nx">getX</span><span class="p">;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">unboundGetX</span><span class="p">());</span><span class="w"> </span><span class="c1">// The function gets invoked at the global scope</span> <span class="c1">// emits undefined as &#39;x&#39; is not specified in global scope.</span> <span class="kd">var</span><span class="w"> </span><span class="nx">boundGetX</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">unboundGetX</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="nx">module</span><span class="p">);</span><span class="w"> </span><span class="c1">// specify object module as the closure</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">boundGetX</span><span class="p">());</span><span class="w"> </span><span class="c1">// emits 42</span> </pre></div> <div class="mw-heading mw-heading3"><h3 id="Example_2:_Accidental_reference_to_a_bound_variable">Example 2: Accidental reference to a bound variable</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=11" title="Edit section: Example 2: Accidental reference to a bound variable"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>For this example the expected behaviour would be that each link should emit its id when clicked; but because the variable 'e' is bound to the scope above, and lazy evaluated on click, what actually happens is that each on click event emits the id of the last element in 'elements' bound at the end of the for loop.<sup id="cite_ref-16" class="reference"><a href="#cite_note-16"><span class="cite-bracket">&#91;</span>14<span class="cite-bracket">&#93;</span></a></sup> </p> <div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="kd">var</span><span class="w"> </span><span class="nx">elements</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByTagName</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">);</span> <span class="c1">// Incorrect: e is bound to the function containing the &#39;for&#39; loop, not the closure of &quot;handle&quot;</span> <span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kd">var</span><span class="w"> </span><span class="nx">e</span><span class="w"> </span><span class="k">of</span><span class="w"> </span><span class="nx">elements</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span> <span class="w"> </span><span class="nx">e</span><span class="p">.</span><span class="nx">onclick</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="w"> </span><span class="nx">handle</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span> <span class="w"> </span><span class="nx">alert</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">id</span><span class="p">);</span> <span class="w"> </span><span class="p">}</span><span class="w"> </span> <span class="p">}</span> </pre></div> <p>Again here variable <code>e</code> would need to be bound by the scope of the block using <code>handle.bind(this)</code> or the <code>let</code> keyword. </p><p>On the other hand, many functional languages, such as <a href="/wiki/ML_(programming_language)" title="ML (programming language)">ML</a>, bind variables directly to values. In this case, since there is no way to change the value of the variable once it is bound, there is no need to share the state between closures—they just use the same values. This is often called capturing the variable "by value". Java's local and anonymous classes also fall into this category—they require captured local variables to be <code>final</code>, which also means there is no need to share state. </p><p>Some languages enable choosing between capturing the value of a variable or its location. For example, in C++11, captured variables are either declared with <code>[&amp;]</code>, which means captured by reference, or with <code>[=]</code>, which means captured by value. </p><p>Yet another subset, <a href="/wiki/Lazy_evaluation" title="Lazy evaluation">lazy</a> functional languages such as <a href="/wiki/Haskell" title="Haskell">Haskell</a>, bind variables to results of future computations rather than values. Consider this example in Haskell: </p> <div class="mw-highlight mw-highlight-lang-haskell mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">-- Haskell</span> <span class="nf">foo</span><span class="w"> </span><span class="ow">::</span><span class="w"> </span><span class="kt">Fractional</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">=&gt;</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">a</span><span class="p">)</span> <span class="nf">foo</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="n">y</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="p">(</span><span class="nf">\</span><span class="n">z</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">z</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">r</span><span class="p">)</span> <span class="w"> </span><span class="kr">where</span><span class="w"> </span><span class="n">r</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">y</span> <span class="nf">f</span><span class="w"> </span><span class="ow">::</span><span class="w"> </span><span class="kt">Fractional</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">=&gt;</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">a</span> <span class="nf">f</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="n">foo</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="mi">0</span> <span class="nf">main</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="n">print</span><span class="w"> </span><span class="p">(</span><span class="n">f</span><span class="w"> </span><span class="mi">123</span><span class="p">)</span> </pre></div> <p>The binding of <code>r</code> captured by the closure defined within function <code>foo</code> is to the computation <code>(x / y)</code>—which in this case results in division by zero. However, since it is the computation that is captured, and not the value, the error only manifests when the closure is invoked, and then attempts to use the captured binding. </p> <div class="mw-heading mw-heading3"><h3 id="Closure_leaving">Closure leaving</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=12" title="Edit section: Closure leaving"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>Yet more differences manifest themselves in the behavior of other lexically scoped constructs, such as <code>return</code>, <code>break</code> and <code>continue</code> statements. Such constructs can, in general, be considered in terms of invoking an <a href="/wiki/Escape_continuation" class="mw-redirect" title="Escape continuation">escape continuation</a> established by an enclosing control statement (in case of <code>break</code> and <code>continue</code>, such interpretation requires looping constructs to be considered in terms of recursive function calls). In some languages, such as ECMAScript, <code>return</code> refers to the continuation established by the closure lexically innermost with respect to the statement—thus, a <code>return</code> within a closure transfers control to the code that called it. However, in <a href="/wiki/Smalltalk" title="Smalltalk">Smalltalk</a>, the superficially similar operator <code>^</code> invokes the escape continuation established for the method invocation, ignoring the escape continuations of any intervening nested closures. The escape continuation of a particular closure can only be invoked in Smalltalk implicitly by reaching the end of the closure's code. These examples in ECMAScript and Smalltalk highlight the difference: </p> <div class="mw-highlight mw-highlight-lang-smalltalk mw-content-ltr" dir="ltr"><pre><span></span><span class="c">&quot;Smalltalk&quot;</span> <span class="nf">foo</span> <span class="o">|</span><span class="nv"> xs </span><span class="o">|</span> <span class="nv">xs</span> <span class="o">:=</span> <span class="ss">#(</span><span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span><span class="ss">)</span><span class="p">.</span> <span class="nv">xs</span> <span class="nf">do:</span> [<span class="o">:</span><span class="nv">x</span> <span class="o">|</span> <span class="o">^</span><span class="nv">x</span>]<span class="p">.</span> <span class="o">^</span><span class="m">0</span> <span class="nf">bar</span> <span class="nf">Transcript</span> <span class="nf">show:</span> (<span class="bp">self</span> <span class="nf">foo</span> <span class="nf">printString</span>) <span class="c">&quot;prints 1&quot;</span> </pre></div> <div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">// ECMAScript</span> <span class="kd">function</span><span class="w"> </span><span class="nx">foo</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">xs</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mf">1</span><span class="p">,</span><span class="w"> </span><span class="mf">2</span><span class="p">,</span><span class="w"> </span><span class="mf">3</span><span class="p">,</span><span class="w"> </span><span class="mf">4</span><span class="p">];</span> <span class="w"> </span><span class="nx">xs</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span><span class="w"> </span><span class="p">(</span><span class="nx">x</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">});</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mf">0</span><span class="p">;</span> <span class="p">}</span> <span class="nx">alert</span><span class="p">(</span><span class="nx">foo</span><span class="p">());</span><span class="w"> </span><span class="c1">// prints 0</span> </pre></div> <p>The above code snippets will behave differently because the Smalltalk <code>^</code> operator and the JavaScript <code>return</code> operator are not analogous. In the ECMAScript example, <code>return x</code> will leave the inner closure to begin a new iteration of the <code>forEach</code> loop, whereas in the Smalltalk example, <code>^x</code> will abort the loop and return from the method <code>foo</code>. </p><p><a href="/wiki/Common_Lisp" title="Common Lisp">Common Lisp</a> provides a construct that can express either of the above actions: Lisp <code>(return-from foo x)</code> behaves as <a href="/wiki/Smalltalk" title="Smalltalk">Smalltalk</a> <code>^x</code>, while Lisp <code>(return-from nil x)</code> behaves as <a href="/wiki/JavaScript" title="JavaScript">JavaScript</a> <code>return x</code>. Hence, Smalltalk makes it possible for a captured escape continuation to outlive the extent in which it can be successfully invoked. Consider: </p> <div class="mw-highlight mw-highlight-lang-smalltalk mw-content-ltr" dir="ltr"><pre><span></span><span class="c">&quot;Smalltalk&quot;</span> <span class="nf">foo</span> <span class="o">^</span>[ <span class="o">:</span><span class="nv">x</span> <span class="o">|</span> <span class="o">^</span><span class="nv">x</span> ] <span class="nf">bar</span> <span class="nf">|</span> <span class="nv">f</span> <span class="nf">|</span> <span class="nv">f</span> <span class="o">:=</span> <span class="bp">self</span> <span class="nf">foo</span><span class="p">.</span> <span class="nv">f</span> <span class="nf">value:</span> <span class="m">123</span> <span class="c">&quot;error!&quot;</span> </pre></div> <p>When the closure returned by the method <code>foo</code> is invoked, it attempts to return a value from the invocation of <code>foo</code> that created the closure. Since that call has already returned and the Smalltalk method invocation model does not follow the <a href="/wiki/Spaghetti_stack" class="mw-redirect" title="Spaghetti stack">spaghetti stack</a> discipline to facilitate multiple returns, this operation results in an error. </p><p>Some languages, such as <a href="/wiki/Ruby_(programming_language)" title="Ruby (programming language)">Ruby</a>, enable the programmer to choose the way <code>return</code> is captured. An example in Ruby: </p> <div class="mw-highlight mw-highlight-lang-ruby mw-content-ltr" dir="ltr"><pre><span></span><span class="c1"># Ruby</span> <span class="c1"># Closure using a Proc</span> <span class="k">def</span><span class="w"> </span><span class="nf">foo</span> <span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="no">Proc</span><span class="o">.</span><span class="n">new</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">&quot;return from foo from inside proc&quot;</span><span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="n">f</span><span class="o">.</span><span class="n">call</span><span class="w"> </span><span class="c1"># control leaves foo here</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">&quot;return from foo&quot;</span> <span class="k">end</span> <span class="c1"># Closure using a lambda</span> <span class="k">def</span><span class="w"> </span><span class="nf">bar</span> <span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">lambda</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">&quot;return from lambda&quot;</span><span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="n">f</span><span class="o">.</span><span class="n">call</span><span class="w"> </span><span class="c1"># control does not leave bar here</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">&quot;return from bar&quot;</span> <span class="k">end</span> <span class="nb">puts</span><span class="w"> </span><span class="n">foo</span><span class="w"> </span><span class="c1"># prints &quot;return from foo from inside proc&quot;</span> <span class="nb">puts</span><span class="w"> </span><span class="n">bar</span><span class="w"> </span><span class="c1"># prints &quot;return from bar&quot;</span> </pre></div> <p>Both <code>Proc.new</code> and <code>lambda</code> in this example are ways to create a closure, but semantics of the closures thus created are different with respect to the <code>return</code> statement. </p><p>In <a href="/wiki/Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>, definition and scope of the <code>return</code> control statement is explicit (and only arbitrarily named 'return' for the sake of the example). The following is a direct translation of the Ruby sample. </p> <div class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" dir="ltr"><pre><span></span><span class="c1">; Scheme</span> <span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="nb">call/cc</span><span class="w"> </span><span class="nb">call-with-current-continuation</span><span class="p">)</span> <span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">foo</span><span class="p">)</span> <span class="w"> </span><span class="p">(</span><span class="nb">call/cc</span> <span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="p">)</span> <span class="w"> </span><span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">&quot;return from foo from inside proc&quot;</span><span class="p">))</span> <span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="c1">; control leaves foo here</span> <span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">&quot;return from foo&quot;</span><span class="p">))))</span> <span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">)</span> <span class="w"> </span><span class="p">(</span><span class="nb">call/cc</span> <span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="p">)</span> <span class="w"> </span><span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nb">call/cc</span><span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">&quot;return from lambda&quot;</span><span class="p">))))</span> <span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="c1">; control does not leave bar here</span> <span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">&quot;return from bar&quot;</span><span class="p">))))</span> <span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">foo</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints &quot;return from foo from inside proc&quot;</span> <span class="p">(</span><span class="nb">newline</span><span class="p">)</span> <span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints &quot;return from bar&quot;</span> </pre></div> <div class="mw-heading mw-heading2"><h2 id="Closure-like_constructs">Closure-like constructs</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=13" title="Edit section: Closure-like constructs"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>Some languages have features which simulate the behavior of closures. In languages such as <a href="/wiki/C%2B%2B" title="C++">C++</a>, <a href="/wiki/C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a>, <a href="/wiki/D_(programming_language)" title="D (programming language)">D</a>, <a href="/wiki/Java_(programming_language)" title="Java (programming language)">Java</a>, <a href="/wiki/Objective-C" title="Objective-C">Objective-C</a>, and <a href="/wiki/Visual_Basic_(.NET)" title="Visual Basic (.NET)">Visual Basic (.NET)</a> (VB.NET), these features are the result of the language's object-oriented paradigm. </p> <div class="mw-heading mw-heading3"><h3 id="Callbacks_(C)"><span id="Callbacks_.28C.29"></span>Callbacks (C)</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=14" title="Edit section: Callbacks (C)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>Some <a href="/wiki/C_(programming_language)" title="C (programming language)">C</a> libraries support <a href="/wiki/Callback_(computer_programming)" title="Callback (computer programming)">callbacks</a>. This is sometimes implemented by providing two values when registering the callback with the library: a function pointer and a separate <code>void*</code> pointer to arbitrary data of the user's choice. When the library executes the callback function, it passes along the data pointer. This enables the callback to maintain state and to refer to information captured at the time it was registered with the library. The idiom is similar to closures in functionality, but not in syntax. The <code>void*</code> pointer is not <a href="/wiki/Type_safety" title="Type safety">type safe</a> so this C idiom differs from type-safe closures in C#, Haskell or ML. </p><p>Callbacks are used extensively in <a href="/wiki/Graphical_user_interface" title="Graphical user interface">graphical user interface</a> (GUI) <a href="/wiki/Widget_toolkit" title="Widget toolkit">widget toolkits</a> to implement <a href="/wiki/Event-driven_programming" title="Event-driven programming">event-driven programming</a> by associating general functions of graphical widgets (menus, buttons, check boxes, sliders, spinners, etc.) with application-specific functions implementing the specific desired behavior for the application. </p> <div class="mw-heading mw-heading4"><h4 id="Nested_function_and_function_pointer_(C)"><span id="Nested_function_and_function_pointer_.28C.29"></span>Nested function and function pointer (C)</h4><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=15" title="Edit section: Nested function and function pointer (C)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>With a <a href="/wiki/GNU_Compiler_Collection" title="GNU Compiler Collection">GNU Compiler Collection</a> (GCC) extension, a nested function<sup id="cite_ref-17" class="reference"><a href="#cite_note-17"><span class="cite-bracket">&#91;</span>15<span class="cite-bracket">&#93;</span></a></sup> can be used and a function pointer can emulate closures, provided the function does not exit the containing scope. The next example is invalid because <code>adder</code> is a top-level definition (depending on compiler version, it could produce a correct result if compiled with no optimizing, i.e., at <code>-O0</code>): </p> <div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span></span><span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;stdio.h&gt;</span> <span class="k">typedef</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">fn_int_to_int</span><span class="p">)(</span><span class="kt">int</span><span class="p">);</span><span class="w"> </span><span class="c1">// type of function int-&gt;int</span> <span class="n">fn_int_to_int</span><span class="w"> </span><span class="nf">adder</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">number</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">add</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">value</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">number</span><span class="p">;</span><span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">&amp;</span><span class="n">add</span><span class="p">;</span><span class="w"> </span><span class="c1">// &amp; operator is optional here because the name of a function in C is a pointer pointing on itself</span> <span class="p">}</span> <span class="kt">int</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="n">fn_int_to_int</span><span class="w"> </span><span class="n">add10</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">adder</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span> <span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">&quot;%d</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">add10</span><span class="p">(</span><span class="mi">1</span><span class="p">));</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span> <span class="p">}</span> </pre></div> <p>But moving <code>adder</code> (and, optionally, the <code>typedef</code>) in <code>main</code> makes it valid: </p> <div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span></span><span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;stdio.h&gt;</span> <span class="kt">int</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">typedef</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">fn_int_to_int</span><span class="p">)(</span><span class="kt">int</span><span class="p">);</span><span class="w"> </span><span class="c1">// type of function int-&gt;int</span> <span class="w"> </span> <span class="w"> </span><span class="n">fn_int_to_int</span><span class="w"> </span><span class="n">adder</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">number</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">add</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">value</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">number</span><span class="p">;</span><span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">add</span><span class="p">;</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span> <span class="w"> </span><span class="n">fn_int_to_int</span><span class="w"> </span><span class="n">add10</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">adder</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span> <span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">&quot;%d</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">add10</span><span class="p">(</span><span class="mi">1</span><span class="p">));</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span> <span class="p">}</span> </pre></div> <p>If executed this now prints <code>11</code> as expected. </p> <div class="mw-heading mw-heading3"><h3 id="Local_classes_and_lambda_functions_(Java)"><span id="Local_classes_and_lambda_functions_.28Java.29"></span>Local classes and lambda functions (Java)</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=16" title="Edit section: Local classes and lambda functions (Java)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p><a href="/wiki/Java_(programming_language)" title="Java (programming language)">Java</a> enables <a href="/wiki/Class_(object-oriented_programming)" class="mw-redirect" title="Class (object-oriented programming)">classes</a> to be defined inside <a href="/wiki/Method_(object-oriented_programming)" class="mw-redirect" title="Method (object-oriented programming)">methods</a>. These are called <i>local classes</i>. When such classes are not named, they are known as <i><a href="/wiki/Anonymous_class" class="mw-redirect" title="Anonymous class">anonymous classes</a></i> (or anonymous <i>inner</i> classes). A local class (either named or anonymous) may refer to names in lexically enclosing classes, or read-only variables (marked as <code>final</code>) in the lexically enclosing method. </p> <div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span></span><span class="kd">class</span> <span class="nc">CalculationWindow</span><span class="w"> </span><span class="kd">extends</span><span class="w"> </span><span class="n">JFrame</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kd">private</span><span class="w"> </span><span class="kd">volatile</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">result</span><span class="p">;</span> <span class="w"> </span><span class="c1">// ...</span> <span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">calculateInSeparateThread</span><span class="p">(</span><span class="kd">final</span><span class="w"> </span><span class="n">URI</span><span class="w"> </span><span class="n">uri</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="c1">// The expression &quot;new Runnable() { ... }&quot; is an anonymous class implementing the &#39;Runnable&#39; interface.</span> <span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Thread</span><span class="p">(</span> <span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Runnable</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">run</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="c1">// It can read final local variables:</span> <span class="w"> </span><span class="n">calculate</span><span class="p">(</span><span class="n">uri</span><span class="p">);</span> <span class="w"> </span><span class="c1">// It can access private fields of the enclosing class:</span> <span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="p">).</span><span class="na">start</span><span class="p">();</span> <span class="w"> </span><span class="p">}</span> <span class="p">}</span> </pre></div> <p>The capturing of <code>final</code> variables enables capturing variables by value. Even if the variable to capture is non-<code>final</code>, it can always be copied to a temporary <code>final</code> variable just before the class. </p><p>Capturing of variables by reference can be emulated by using a <code>final</code> reference to a mutable container, for example, a one-element array. The local class will not be able to change the value of the container reference, but it will be able to change the contents of the container. </p><p>With the advent of Java 8's lambda expressions,<sup id="cite_ref-18" class="reference"><a href="#cite_note-18"><span class="cite-bracket">&#91;</span>16<span class="cite-bracket">&#93;</span></a></sup> the closure causes the above code to be executed as: </p> <div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span></span><span class="kd">class</span> <span class="nc">CalculationWindow</span><span class="w"> </span><span class="kd">extends</span><span class="w"> </span><span class="n">JFrame</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kd">private</span><span class="w"> </span><span class="kd">volatile</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">result</span><span class="p">;</span> <span class="w"> </span><span class="c1">// ...</span> <span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">calculateInSeparateThread</span><span class="p">(</span><span class="kd">final</span><span class="w"> </span><span class="n">URI</span><span class="w"> </span><span class="n">uri</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="c1">// The code () -&gt; { /* code */ } is a closure.</span> <span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Thread</span><span class="p">(()</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="n">calculate</span><span class="p">(</span><span class="n">uri</span><span class="p">);</span> <span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span> <span class="w"> </span><span class="p">}).</span><span class="na">start</span><span class="p">();</span> <span class="w"> </span><span class="p">}</span> <span class="p">}</span> </pre></div> <p>Local classes are one of the types of <a href="/wiki/Inner_class" title="Inner class">inner class</a> that are declared within the body of a method. Java also supports inner classes that are declared as <i>non-static members</i> of an enclosing class.<sup id="cite_ref-19" class="reference"><a href="#cite_note-19"><span class="cite-bracket">&#91;</span>17<span class="cite-bracket">&#93;</span></a></sup> They are normally referred to just as "inner classes".<sup id="cite_ref-20" class="reference"><a href="#cite_note-20"><span class="cite-bracket">&#91;</span>18<span class="cite-bracket">&#93;</span></a></sup> These are defined in the body of the enclosing class and have full access to instance variables of the enclosing class. Due to their binding to these instance variables, an inner class may only be instantiated with an explicit binding to an instance of the enclosing class using a special syntax.<sup id="cite_ref-21" class="reference"><a href="#cite_note-21"><span class="cite-bracket">&#91;</span>19<span class="cite-bracket">&#93;</span></a></sup> </p> <div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span></span><span class="kd">public</span><span class="w"> </span><span class="kd">class</span> <span class="nc">EnclosingClass</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="cm">/* Define the inner class */</span> <span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kd">class</span> <span class="nc">InnerClass</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">incrementAndReturnCounter</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">counter</span><span class="o">++</span><span class="p">;</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="kd">private</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">counter</span><span class="p">;</span> <span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="n">counter</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">getCounter</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">counter</span><span class="p">;</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="n">EnclosingClass</span><span class="w"> </span><span class="n">enclosingClassInstance</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">EnclosingClass</span><span class="p">();</span> <span class="w"> </span><span class="cm">/* Instantiate the inner class, with binding to the instance */</span> <span class="w"> </span><span class="n">EnclosingClass</span><span class="p">.</span><span class="na">InnerClass</span><span class="w"> </span><span class="n">innerClassInstance</span><span class="w"> </span><span class="o">=</span> <span class="w"> </span><span class="n">enclosingClassInstance</span><span class="p">.</span><span class="na">new</span><span class="w"> </span><span class="nf">InnerClass</span><span class="p">();</span> <span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">enclosingClassInstance</span><span class="p">.</span><span class="na">getCounter</span><span class="p">();</span> <span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">innerClassInstance</span><span class="p">.</span><span class="na">incrementAndReturnCounter</span><span class="p">())</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span> <span class="w"> </span><span class="cm">/* increment step omitted */</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="n">i</span><span class="p">);</span> <span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="p">}</span> <span class="p">}</span> </pre></div> <p>Upon execution, this will print the integers from 0 to 9. Beware to not confuse this type of class with the nested class, which is declared in the same way with an accompanied usage of the "static" modifier; those have not the desired effect but are instead just classes with no special binding defined in an enclosing class. </p><p>As of <a href="/wiki/Java_version_history#Java_8" title="Java version history">Java 8</a>, Java supports functions as first class objects. Lambda expressions of this form are considered of type <code>Function&lt;T,U&gt;</code> with T being the domain and U the image type. The expression can be called with its <code>.apply(T t)</code> method, but not with a standard method call. </p> <div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span></span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="n">Function</span><span class="o">&lt;</span><span class="n">String</span><span class="p">,</span><span class="w"> </span><span class="n">Integer</span><span class="o">&gt;</span><span class="w"> </span><span class="n">length</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">s</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="na">length</span><span class="p">();</span> <span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="w"> </span><span class="n">length</span><span class="p">.</span><span class="na">apply</span><span class="p">(</span><span class="s">&quot;Hello, world!&quot;</span><span class="p">)</span><span class="w"> </span><span class="p">);</span><span class="w"> </span><span class="c1">// Will print 13.</span> <span class="p">}</span> </pre></div> <div class="mw-heading mw-heading3"><h3 id="Blocks_(C,_C++,_Objective-C_2.0)"><span id="Blocks_.28C.2C_C.2B.2B.2C_Objective-C_2.0.29"></span>Blocks (C, C++, Objective-C 2.0)</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=17" title="Edit section: Blocks (C, C++, Objective-C 2.0)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1236090951"><div role="note" class="hatnote navigation-not-searchable">Main article: <a href="/wiki/Blocks_(C_language_extension)" title="Blocks (C language extension)">Blocks (C language extension)</a></div> <p><a href="/wiki/Apple_Inc." title="Apple Inc.">Apple</a> introduced <a href="/wiki/Blocks_(C_language_extension)" title="Blocks (C language extension)">blocks</a>, a form of closure, as a nonstandard extension into <a href="/wiki/C_(programming_language)" title="C (programming language)">C</a>, <a href="/wiki/C%2B%2B" title="C++">C++</a>, <a href="/wiki/Objective-C_2.0" class="mw-redirect" title="Objective-C 2.0">Objective-C 2.0</a> and in <a href="/wiki/Mac_OS_X_Snow_Leopard" title="Mac OS X Snow Leopard">Mac OS X 10.6 "Snow Leopard"</a> and <a href="/wiki/IOS_4" title="IOS 4">iOS 4</a>.0. Apple made their implementation available for the GCC and clang compilers. </p><p>Pointers to block and block literals are marked with <code>^</code>. Normal local variables are captured by value when the block is created, and are read-only inside the block. Variables to be captured by reference are marked with <code>__block</code>. Blocks that need to persist outside of the scope they are created in may need to be copied.<sup id="cite_ref-22" class="reference"><a href="#cite_note-22"><span class="cite-bracket">&#91;</span>20<span class="cite-bracket">&#93;</span></a></sup><sup id="cite_ref-23" class="reference"><a href="#cite_note-23"><span class="cite-bracket">&#91;</span>21<span class="cite-bracket">&#93;</span></a></sup> </p> <div class="mw-highlight mw-highlight-lang-objc mw-content-ltr" dir="ltr"><pre><span></span><span class="k">typedef</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">(</span><span class="o">^</span><span class="n">IntBlock</span><span class="p">)();</span> <span class="n">IntBlock</span><span class="w"> </span><span class="nf">downCounter</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">start</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">__block</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">start</span><span class="p">;</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">[[</span><span class="w"> </span><span class="o">^</span><span class="kt">int</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">i</span><span class="o">--</span><span class="p">;</span> <span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">copy</span><span class="p">]</span><span class="w"> </span><span class="n">autorelease</span><span class="p">];</span> <span class="p">}</span> <span class="n">IntBlock</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">downCounter</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span> <span class="n">NSLog</span><span class="p">(</span><span class="s">@&quot;%d&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">f</span><span class="p">());</span> <span class="n">NSLog</span><span class="p">(</span><span class="s">@&quot;%d&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">f</span><span class="p">());</span> <span class="n">NSLog</span><span class="p">(</span><span class="s">@&quot;%d&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">f</span><span class="p">());</span> </pre></div> <div class="mw-heading mw-heading3"><h3 id="Delegates_(C#,_VB.NET,_D)"><span id="Delegates_.28C.23.2C_VB.NET.2C_D.29"></span>Delegates (C#, VB.NET, D)</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=18" title="Edit section: Delegates (C#, VB.NET, D)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p><a href="/wiki/C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a> anonymous methods and lambda expressions support closure: </p> <div class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><pre><span></span><span class="kt">var</span><span class="w"> </span><span class="n">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="p">[]</span><span class="w"> </span><span class="p">{</span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="m">2</span><span class="p">,</span><span class="w"> </span><span class="m">3</span><span class="p">,</span><span class="w"> </span><span class="m">4</span><span class="p">};</span> <span class="kt">var</span><span class="w"> </span><span class="n">multiplier</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span><span class="p">;</span> <span class="kt">var</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">data</span><span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">x</span><span class="w"> </span><span class="o">=&gt;</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">multiplier</span><span class="p">);</span> </pre></div> <p><a href="/wiki/Visual_Basic_.NET" class="mw-redirect" title="Visual Basic .NET">Visual Basic .NET</a>, which has many language features similar to those of C#, also supports lambda expressions with closures: </p> <div class="mw-highlight mw-highlight-lang-vb.net mw-content-ltr" dir="ltr"><pre><span></span><span class="k">Dim</span><span class="w"> </span><span class="n">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">,</span><span class="w"> </span><span class="mi">4</span><span class="p">}</span> <span class="k">Dim</span><span class="w"> </span><span class="n">multiplier</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span> <span class="k">Dim</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">data</span><span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">Function</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">multiplier</span><span class="p">)</span> </pre></div> <p>In <a href="/wiki/D_(programming_language)" title="D (programming language)">D</a>, closures are implemented by delegates, a function pointer paired with a context pointer (e.g. a class instance, or a stack frame on the heap in the case of closures). </p> <div class="mw-highlight mw-highlight-lang-d mw-content-ltr" dir="ltr"><pre><span></span><span class="k">auto</span><span class="w"> </span><span class="n">test1</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="k">delegate</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">+</span><span class="w"> </span><span class="mi">3</span><span class="p">;</span><span class="w"> </span><span class="p">};</span><span class="w"> </span><span class="c1">// anonymous delegate construction</span> <span class="p">}</span> <span class="k">auto</span><span class="w"> </span><span class="n">test2</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">20</span><span class="p">;</span> <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">foo</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">+</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="c1">// inner function</span> <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">&amp;</span><span class="n">foo</span><span class="p">;</span><span class="w"> </span><span class="c1">// other way to construct delegate</span> <span class="p">}</span> <span class="kt">void</span><span class="w"> </span><span class="n">bar</span><span class="p">()</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="k">auto</span><span class="w"> </span><span class="n">dg</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">test1</span><span class="p">();</span> <span class="w"> </span><span class="n">dg</span><span class="p">();</span><span class="w"> </span><span class="c1">// =10 // ok, test1.a is in a closure and still exists</span> <span class="w"> </span><span class="n">dg</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">test2</span><span class="p">();</span> <span class="w"> </span><span class="n">dg</span><span class="p">();</span><span class="w"> </span><span class="c1">// =25 // ok, test2.a is in a closure and still exists</span> <span class="p">}</span> </pre></div> <p>D version 1, has limited closure support. For example, the above code will not work correctly, because the variable a is on the stack, and after returning from test(), it is no longer valid to use it (most probably calling foo via dg(), will return a 'random' integer). This can be solved by explicitly allocating the variable 'a' on heap, or using structs or class to store all needed closed variables and construct a delegate from a method implementing the same code. Closures can be passed to other functions, as long as they are only used while the referenced values are still valid (for example calling another function with a closure as a callback parameter), and are useful for writing generic data processing code, so this limitation, in practice, is often not an issue. </p><p>This limitation was fixed in D version 2 - the variable 'a' will be automatically allocated on the heap because it is used in the inner function, and a delegate of that function can escape the current scope (via assignment to dg or return). Any other local variables (or arguments) that are not referenced by delegates or that are only referenced by delegates that do not escape the current scope, remain on the stack, which is simpler and faster than heap allocation. The same is true for inner's class methods that reference a function's variables. </p> <div class="mw-heading mw-heading3"><h3 id="Function_objects_(C++)"><span id="Function_objects_.28C.2B.2B.29"></span>Function objects (C++)</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=19" title="Edit section: Function objects (C++)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p><a href="/wiki/C%2B%2B" title="C++">C++</a> enables defining <a href="/wiki/Function_object" title="Function object">function objects</a> by overloading <code>operator()</code>. These objects behave somewhat like functions in a functional programming language. They may be created at runtime and may contain state, but they do not implicitly capture local variables as closures do. As of <a href="/wiki/C%2B%2B11" title="C++11">the 2011 revision</a>, the C++ language also supports closures, which are a type of function object constructed automatically from a special language construct called <i>lambda-expression</i>. A C++ closure may capture its context either by storing copies of the accessed variables as members of the closure object or by reference. In the latter case, if the closure object escapes the scope of a referenced object, invoking its <code>operator()</code> causes undefined behavior since C++ closures do not extend the lifetime of their context.<link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1236090951"></p><div role="note" class="hatnote navigation-not-searchable">Main article: <a href="/wiki/Anonymous_function#C++_(since_C++11)" title="Anonymous function">Anonymous function §&#160;C++ (since C++11)</a></div> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span></span><span class="kt">void</span><span class="w"> </span><span class="nf">foo</span><span class="p">(</span><span class="n">string</span><span class="w"> </span><span class="n">myname</span><span class="p">)</span><span class="w"> </span><span class="p">{</span> <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">y</span><span class="p">;</span> <span class="w"> </span><span class="n">vector</span><span class="o">&lt;</span><span class="n">string</span><span class="o">&gt;</span><span class="w"> </span><span class="n">n</span><span class="p">;</span> <span class="w"> </span><span class="c1">// ...</span> <span class="w"> </span><span class="k">auto</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">std</span><span class="o">::</span><span class="n">find_if</span><span class="p">(</span><span class="n">n</span><span class="p">.</span><span class="n">begin</span><span class="p">(),</span><span class="w"> </span><span class="n">n</span><span class="p">.</span><span class="n">end</span><span class="p">(),</span> <span class="w"> </span><span class="c1">// this is the lambda expression:</span> <span class="w"> </span><span class="p">[</span><span class="o">&amp;</span><span class="p">](</span><span class="k">const</span><span class="w"> </span><span class="n">string</span><span class="o">&amp;</span><span class="w"> </span><span class="n">s</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">s</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="n">myname</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="n">size</span><span class="p">()</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">y</span><span class="p">;</span><span class="w"> </span><span class="p">}</span> <span class="w"> </span><span class="p">);</span> <span class="w"> </span><span class="c1">// &#39;i&#39; is now either &#39;n.end()&#39; or points to the first string in &#39;n&#39;</span> <span class="w"> </span><span class="c1">// which is not equal to &#39;myname&#39; and whose length is greater than &#39;y&#39;</span> <span class="p">}</span> </pre></div> <div class="mw-heading mw-heading3"><h3 id="Inline_agents_(Eiffel)"><span id="Inline_agents_.28Eiffel.29"></span>Inline agents (Eiffel)</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=20" title="Edit section: Inline agents (Eiffel)"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p><a href="/wiki/Eiffel_(programming_language)" title="Eiffel (programming language)">Eiffel</a> includes inline agents defining closures. An inline agent is an object representing a routine, defined by giving the code of the routine in-line. For example, in </p> <div class="mw-highlight mw-highlight-lang-eiffel mw-content-ltr" dir="ltr"><pre><span></span><span class="n">ok_button</span><span class="p">.</span><span class="n">click_event</span><span class="p">.</span><span class="n">subscribe</span><span class="w"> </span><span class="p">(</span> <span class="w"> </span><span class="kr">agent</span><span class="w"> </span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="n">y</span><span class="p">:</span><span class="w"> </span><span class="nc">INTEGER</span><span class="p">)</span><span class="w"> </span><span class="kr">do</span> <span class="w"> </span><span class="n">map</span><span class="p">.</span><span class="n">country_at_coordinates</span><span class="w"> </span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="n">y</span><span class="p">).</span><span class="n">display</span> <span class="w"> </span><span class="kr">end</span> <span class="p">)</span> </pre></div> <p>the argument to <code>subscribe</code> is an agent, representing a procedure with two arguments; the procedure finds the country at the corresponding coordinates and displays it. The whole agent is "subscribed" to the event type <code>click_event</code> for a certain button, so that whenever an instance of the event type occurs on that button – because a user has clicked the button – the procedure will be executed with the mouse coordinates being passed as arguments for <code>x</code> and <code>y</code>. </p><p>The main limitation of Eiffel agents, which distinguishes them from closures in other languages, is that they cannot reference local variables from the enclosing scope. This design decision helps in avoiding ambiguity when talking about a local variable value in a closure - should it be the latest value of the variable or the value captured when the agent is created? Only <code>Current</code> (a reference to current object, analogous to <code>this</code> in Java), its features, and arguments of the agent can be accessed from within the agent body. The values of the outer local variables can be passed by providing additional closed operands to the agent. </p> <div class="mw-heading mw-heading3"><h3 id="C++Builder_closure_reserved_word"><span id="C.2B.2BBuilder_closure_reserved_word"></span>C++Builder __closure reserved word</h3><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=21" title="Edit section: C++Builder __closure reserved word"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <p>Embarcadero C++Builder provides the reserved word <code>__closure</code> to provide a pointer to a method with a similar syntax to a function pointer.<sup id="cite_ref-24" class="reference"><a href="#cite_note-24"><span class="cite-bracket">&#91;</span>22<span class="cite-bracket">&#93;</span></a></sup> </p><p> Standard C allows writing a <style data-mw-deduplicate="TemplateStyles:r886049734">.mw-parser-output .monospaced{font-family:monospace,monospace}</style><span class="monospaced"><a href="/wiki/Typedef" title="Typedef">typedef</a></span> for a pointer to a <a href="/wiki/Function_type" title="Function type">function type</a> using the following syntax:</p><div class="mw-highlight mw-highlight-lang-c++ mw-content-ltr" dir="ltr"><pre><span></span><span class="k">typedef</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">TMyFunctionPointer</span><span class="p">)(</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="p">);</span> </pre></div><p>In a similar way, a <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r886049734"><span class="monospaced">typedef</span> can be declared for a pointer to a method using this syntax:</p><div class="mw-highlight mw-highlight-lang-c++ mw-content-ltr" dir="ltr"><pre><span></span><span class="k">typedef</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="p">(</span><span class="n">__closure</span><span class="w"> </span><span class="o">*</span><span class="n">TMyMethodPointer</span><span class="p">)();</span> </pre></div> <div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=22" title="Edit section: See also"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <style data-mw-deduplicate="TemplateStyles:r1184024115">.mw-parser-output .div-col{margin-top:0.3em;column-width:30em}.mw-parser-output .div-col-small{font-size:90%}.mw-parser-output .div-col-rules{column-rule:1px solid #aaa}.mw-parser-output .div-col dl,.mw-parser-output .div-col ol,.mw-parser-output .div-col ul{margin-top:0}.mw-parser-output .div-col li,.mw-parser-output .div-col dd{page-break-inside:avoid;break-inside:avoid-column}</style><div class="div-col"> <ul><li><a href="/wiki/Command_pattern" title="Command pattern">Command pattern</a></li> <li><a href="/wiki/Currying" title="Currying">Currying</a></li> <li><a href="/wiki/Lambda_calculus" title="Lambda calculus">Lambda calculus</a></li> <li><a href="/wiki/Partial_application" title="Partial application">Partial application</a></li> <li><a href="/wiki/Syntactic_closure" title="Syntactic closure">Syntactic closure</a></li> <li><a href="/wiki/Value-level_programming" title="Value-level programming">Value-level programming</a></li></ul> </div> <div class="mw-heading mw-heading2"><h2 id="Notes">Notes</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=23" title="Edit section: Notes"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <style data-mw-deduplicate="TemplateStyles:r1239543626">.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}</style><div class="reflist reflist-lower-alpha"> <div class="mw-references-wrap"><ol class="references"> <li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text">The function may be stored as a <a href="/wiki/Reference_(computer_science)" title="Reference (computer science)">reference</a> to a function, such as a <a href="/wiki/Function_pointer" title="Function pointer">function pointer</a>.</span> </li> <li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text">These names usually refer to values, mutable variables, or functions, but can also be other entities such as constants, types, classes, or labels.</span> </li> </ol></div></div> <div class="mw-heading mw-heading2"><h2 id="References">References</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=24" title="Edit section: References"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1239543626"><div class="reflist reflist-columns references-column-width" style="column-width: 30em;"> <ol class="references"> <li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text">Sussman and Steele. "Scheme: An interpreter for extended lambda calculus". "... a data structure containing a lambda expression, and an environment to be used when that lambda expression is applied to arguments." (<a href="https://en.wikisource.org/wiki/Page:Scheme_-_An_interpreter_for_extended_lambda_calculus.djvu/22" class="extiw" title="s:Page:Scheme - An interpreter for extended lambda calculus.djvu/22">Wikisource</a>)</span> </li> <li id="cite_note-dat2012-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-dat2012_4-0">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("//upload.wikimedia.org/wikipedia/commons/6/65/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("//upload.wikimedia.org/wikipedia/commons/d/d6/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("//upload.wikimedia.org/wikipedia/commons/a/aa/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("//upload.wikimedia.org/wikipedia/commons/4/4c/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}</style><cite id="CITEREFTurner2012" class="citation conference cs1"><a href="/wiki/David_A._Turner" class="mw-redirect" title="David A. Turner">Turner, David A.</a> (2012). <a rel="nofollow" class="external text" href="http://www.cs.kent.ac.uk/people/staff/dat/tfp12/tfp12.pdf">"Some History of Functional Programming Languages"</a> <span class="cs1-format">(PDF)</span>. <i>International Symposium on Trends in Functional Programming</i>. Lecture Notes in Computer Science. Vol.&#160;7829. Springer. pp.&#160;1–20 See 12 §2, note 8 for the claim about M-expressions. <a href="/wiki/Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1007%2F978-3-642-40447-4_1">10.1007/978-3-642-40447-4_1</a>. <a href="/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&#160;<a href="/wiki/Special:BookSources/978-3-642-40447-4" title="Special:BookSources/978-3-642-40447-4"><bdi>978-3-642-40447-4</bdi></a>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=conference&amp;rft.atitle=Some+History+of+Functional+Programming+Languages&amp;rft.btitle=International+Symposium+on+Trends+in+Functional+Programming&amp;rft.series=Lecture+Notes+in+Computer+Science&amp;rft.pages=1-20+See+12+%C2%A72%2C+note+8+for+the+claim+about+M-expressions&amp;rft.pub=Springer&amp;rft.date=2012&amp;rft_id=info%3Adoi%2F10.1007%2F978-3-642-40447-4_1&amp;rft.isbn=978-3-642-40447-4&amp;rft.aulast=Turner&amp;rft.aufirst=David+A.&amp;rft_id=http%3A%2F%2Fwww.cs.kent.ac.uk%2Fpeople%2Fstaff%2Fdat%2Ftfp12%2Ftfp12.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-landin-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-landin_5-0">^</a></b></span> <span class="reference-text"> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFLandin1964" class="citation journal cs1"><a href="/wiki/Peter_Landin" title="Peter Landin">Landin, P.J.</a> (January 1964). <a rel="nofollow" class="external text" href="https://academic.oup.com/comjnl/article-pdf/6/4/308/1067901/6-4-308.pdf">"The mechanical evaluation of expressions"</a> <span class="cs1-format">(PDF)</span>. <i>The Computer Journal</i>. <b>6</b> (4): 308–320. <a href="/wiki/Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1093%2Fcomjnl%2F6.4.308">10.1093/comjnl/6.4.308</a>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=The+Computer+Journal&amp;rft.atitle=The+mechanical+evaluation+of+expressions&amp;rft.volume=6&amp;rft.issue=4&amp;rft.pages=308-320&amp;rft.date=1964-01&amp;rft_id=info%3Adoi%2F10.1093%2Fcomjnl%2F6.4.308&amp;rft.aulast=Landin&amp;rft.aufirst=P.J.&amp;rft_id=https%3A%2F%2Facademic.oup.com%2Fcomjnl%2Farticle-pdf%2F6%2F4%2F308%2F1067901%2F6-4-308.pdf&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text"> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFMoses1970" class="citation journal cs1"><a href="/wiki/Joel_Moses" title="Joel Moses">Moses, Joel</a> (June 1970). "The Function of FUNCTION in LISP, or Why the FUNARG Problem Should Be Called the Environment Problem". <i>ACM SIGSAM Bulletin</i> (15): 13–27. <a href="/wiki/Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F1093410.1093411">10.1145/1093410.1093411</a>. <a href="/wiki/Hdl_(identifier)" class="mw-redirect" title="Hdl (identifier)">hdl</a>:<a rel="nofollow" class="external text" href="https://hdl.handle.net/1721.1%2F5854">1721.1/5854</a>. <a href="/wiki/S2CID_(identifier)" class="mw-redirect" title="S2CID (identifier)">S2CID</a>&#160;<a rel="nofollow" class="external text" href="https://api.semanticscholar.org/CorpusID:17514262">17514262</a>. <a href="/wiki/AI_Memo" title="AI Memo">AI Memo</a> 199. <q>A useful metaphor for the difference between FUNCTION and QUOTE in LISP is to think of QUOTE as a porous or an open covering of the function since free variables escape to the current environment. FUNCTION acts as a closed or nonporous covering (hence the term "closure" used by Landin). Thus we talk of "open" Lambda expressions (functions in LISP are usually Lambda expressions) and "closed" Lambda expressions. [...] My interest in the environment problem began while Landin, who had a deep understanding of the problem, visited MIT during 1966–67. I then realized the correspondence between the FUNARG lists which are the results of the evaluation of "closed" Lambda expressions in <a href="/wiki/LISP_1.5" class="mw-redirect" title="LISP 1.5">LISP</a> and <a href="/wiki/ISWIM" title="ISWIM">ISWIM</a>'s Lambda Closures.</q></cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=article&amp;rft.jtitle=ACM+SIGSAM+Bulletin&amp;rft.atitle=The+Function+of+FUNCTION+in+LISP%2C+or+Why+the+FUNARG+Problem+Should+Be+Called+the+Environment+Problem&amp;rft.issue=15&amp;rft.pages=13-27&amp;rft.date=1970-06&amp;rft_id=info%3Ahdl%2F1721.1%2F5854&amp;rft_id=https%3A%2F%2Fapi.semanticscholar.org%2FCorpusID%3A17514262%23id-name%3DS2CID&amp;rft_id=info%3Adoi%2F10.1145%2F1093410.1093411&amp;rft.aulast=Moses&amp;rft.aufirst=Joel&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFWikström1987" class="citation book cs1">Wikström, Åke (1987). <i>Functional Programming using Standard ML</i>. Prentice Hall. <a href="/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&#160;<a href="/wiki/Special:BookSources/0-13-331968-7" title="Special:BookSources/0-13-331968-7"><bdi>0-13-331968-7</bdi></a>. <q>The reason it is called a "closure" is that an expression containing free variables is called an "open" expression, and by associating to it the bindings of its free variables, you close it.</q></cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Functional+Programming+using+Standard+ML&amp;rft.pub=Prentice+Hall&amp;rft.date=1987&amp;rft.isbn=0-13-331968-7&amp;rft.aulast=Wikstr%C3%B6m&amp;rft.aufirst=%C3%85ke&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-8">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFSussmanSteele1975" class="citation report cs1"><a href="/wiki/Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman, Gerald Jay</a>; <a href="/wiki/Guy_L._Steele_Jr." title="Guy L. Steele Jr.">Steele, Guy L. Jr.</a> (December 1975). Scheme: An Interpreter for the Extended Lambda Calculus (Report). <a href="/wiki/AI_Memo" title="AI Memo">AI Memo</a> 349.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=report&amp;rft.btitle=Scheme%3A+An+Interpreter+for+the+Extended+Lambda+Calculus&amp;rft.date=1975-12&amp;rft.aulast=Sussman&amp;rft.aufirst=Gerald+Jay&amp;rft.au=Steele%2C+Guy+L.+Jr.&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-9"><span class="mw-cite-backlink"><b><a href="#cite_ref-9">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFAbelsonSussmanSussman1996" class="citation book cs1"><a href="/wiki/Harold_Abelson" class="mw-redirect" title="Harold Abelson">Abelson, Harold</a>; <a href="/wiki/Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman, Gerald Jay</a>; <a href="/wiki/Julie_Sussman" class="mw-redirect" title="Julie Sussman">Sussman, Julie</a> (1996). <a rel="nofollow" class="external text" href="https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html"><i>Structure and Interpretation of Computer Programs</i></a>. MIT Press. pp.&#160;98–99. <a href="/wiki/ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&#160;<a href="/wiki/Special:BookSources/0-262-51087-1" title="Special:BookSources/0-262-51087-1"><bdi>0-262-51087-1</bdi></a>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=Structure+and+Interpretation+of+Computer+Programs&amp;rft.pages=98-99&amp;rft.pub=MIT+Press&amp;rft.date=1996&amp;rft.isbn=0-262-51087-1&amp;rft.aulast=Abelson&amp;rft.aufirst=Harold&amp;rft.au=Sussman%2C+Gerald+Jay&amp;rft.au=Sussman%2C+Julie&amp;rft_id=https%3A%2F%2Fmitpress.mit.edu%2Fsites%2Fdefault%2Ffiles%2Fsicp%2Ffull-text%2Fbook%2Fbook.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-10"><span class="mw-cite-backlink"><b><a href="#cite_ref-10">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter">"array.filter"</a>. <i>Mozilla Developer Center</i>. 10 January 2010<span class="reference-accessdate">. Retrieved <span class="nowrap">9 February</span> 2010</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Mozilla+Developer+Center&amp;rft.atitle=array.filter&amp;rft.date=2010-01-10&amp;rft_id=https%3A%2F%2Fdeveloper.mozilla.org%2Fen%2FCore_JavaScript_1.5_Reference%2FGlobal_Objects%2FArray%2Ffilter&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-11"><span class="mw-cite-backlink"><b><a href="#cite_ref-11">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20081226055307/http://okmij.org/ftp/Scheme/oop-in-fp.txt">"Re: FP, OO and relations. Does anyone trump the others?"</a>. 29 December 1999. Archived from <a rel="nofollow" class="external text" href="http://okmij.org/ftp/Scheme/oop-in-fp.txt">the original</a> on 26 December 2008<span class="reference-accessdate">. Retrieved <span class="nowrap">23 December</span> 2008</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Re%3A+FP%2C+OO+and+relations.+Does+anyone+trump+the+others%3F&amp;rft.date=1999-12-29&amp;rft_id=http%3A%2F%2Fokmij.org%2Fftp%2FScheme%2Foop-in-fp.txt&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-12"><span class="mw-cite-backlink"><b><a href="#cite_ref-12">^</a></b></span> <span class="reference-text"><i><a rel="nofollow" class="external text" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2550.pdf">Lambda Expressions and Closures</a></i> C++ Standards Committee. 29 February 2008.</span> </li> <li id="cite_note-13"><span class="mw-cite-backlink"><b><a href="#cite_ref-13">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html">"6.4 Nested Functions"</a>. <i>GCC Manual</i>. <q>If you try to call the nested function through its address after the containing function exits, all hell breaks loose. If you try to call it after a containing scope level exits, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it's not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.</q></cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=GCC+Manual&amp;rft.atitle=6.4+Nested+Functions&amp;rft_id=https%3A%2F%2Fgcc.gnu.org%2Fonlinedocs%2Fgcc%2FNested-Functions.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-14"><span class="mw-cite-backlink"><b><a href="#cite_ref-14">^</a></b></span> <span class="reference-text"><i><a rel="nofollow" class="external text" href="https://dspace.mit.edu/handle/1721.1/6935">Foundations of Actor Semantics</a></i> Will Clinger. MIT Mathematics Doctoral Dissertation. June 1981.</span> </li> <li id="cite_note-15"><span class="mw-cite-backlink"><b><a href="#cite_ref-15">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">"Function.prototype.bind()"</a>. <i>MDN Web Docs</i><span class="reference-accessdate">. Retrieved <span class="nowrap">20 November</span> 2018</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=MDN+Web+Docs&amp;rft.atitle=Function.prototype.bind%28%29&amp;rft_id=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_objects%2FFunction%2Fbind&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-16"><span class="mw-cite-backlink"><b><a href="#cite_ref-16">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake">"Closures"</a>. <i>MDN Web Docs</i><span class="reference-accessdate">. Retrieved <span class="nowrap">20 November</span> 2018</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=MDN+Web+Docs&amp;rft.atitle=Closures&amp;rft_id=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FJavaScript%2FClosures%23Creating_closures_in_loops_A_common_mistake&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-17"><span class="mw-cite-backlink"><b><a href="#cite_ref-17">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html">"Nested functions"</a>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Nested+functions&amp;rft_id=https%3A%2F%2Fgcc.gnu.org%2Fonlinedocs%2Fgcc%2FNested-Functions.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-18"><span class="mw-cite-backlink"><b><a href="#cite_ref-18">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">"Lambda Expressions"</a>. <i>The Java Tutorials</i>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=The+Java+Tutorials&amp;rft.atitle=Lambda+Expressions&amp;rft_id=http%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ftutorial%2Fjava%2FjavaOO%2Flambdaexpressions.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-19"><span class="mw-cite-backlink"><b><a href="#cite_ref-19">^</a></b></span> <span class="reference-text"> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20160831172734/https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top">"Nested, Inner, Member, and Top-Level Classes"</a>. <i>Joseph D. Darcy's Oracle Weblog</i>. July 2007. Archived from <a rel="nofollow" class="external text" href="https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top">the original</a> on 31 August 2016.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=Joseph+D.+Darcy%27s+Oracle+Weblog&amp;rft.atitle=Nested%2C+Inner%2C+Member%2C+and+Top-Level+Classes&amp;rft.date=2007-07&amp;rft_id=https%3A%2F%2Fblogs.oracle.com%2Fdarcy%2Fentry%2Fnested_inner_member_and_top&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-20"><span class="mw-cite-backlink"><b><a href="#cite_ref-20">^</a></b></span> <span class="reference-text"> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html">"Inner Class Example"</a>. <i>The Java Tutorials: Learning the Java Language: Classes and Objects</i>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=The+Java+Tutorials%3A+Learning+the+Java+Language%3A+Classes+and+Objects&amp;rft.atitle=Inner+Class+Example&amp;rft_id=https%3A%2F%2Fjava.sun.com%2Fdocs%2Fbooks%2Ftutorial%2Fjava%2FjavaOO%2Finnerclasses.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-21"><span class="mw-cite-backlink"><b><a href="#cite_ref-21">^</a></b></span> <span class="reference-text"> <link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://java.sun.com/docs/books/tutorial/java/javaOO/nested.html">"Nested Classes"</a>. <i>The Java Tutorials: Learning the Java Language: Classes and Objects</i>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&amp;rft.genre=unknown&amp;rft.jtitle=The+Java+Tutorials%3A+Learning+the+Java+Language%3A+Classes+and+Objects&amp;rft.atitle=Nested+Classes&amp;rft_id=https%3A%2F%2Fjava.sun.com%2Fdocs%2Fbooks%2Ftutorial%2Fjava%2FjavaOO%2Fnested.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-22"><span class="mw-cite-backlink"><b><a href="#cite_ref-22">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html">"Blocks Programming Topics"</a>. Apple Inc. 8 March 2011<span class="reference-accessdate">. Retrieved <span class="nowrap">8 March</span> 2011</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Blocks+Programming+Topics&amp;rft.pub=Apple+Inc.&amp;rft.date=2011-03-08&amp;rft_id=https%3A%2F%2Fdeveloper.apple.com%2Flibrary%2Fmac%2F%23documentation%2FCocoa%2FConceptual%2FBlocks%2FArticles%2F00_Introduction.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-23"><span class="mw-cite-backlink"><b><a href="#cite_ref-23">^</a></b></span> <span class="reference-text"><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFBengtsson2010" class="citation web cs1">Bengtsson, Joachim (7 July 2010). <a rel="nofollow" class="external text" href="https://web.archive.org/web/20101025034928/http://thirdcog.eu/pwcblocks/">"Programming with C Blocks on Apple Devices"</a>. Archived from <a rel="nofollow" class="external text" href="http://thirdcog.eu/pwcblocks/">the original</a> on 25 October 2010<span class="reference-accessdate">. Retrieved <span class="nowrap">18 September</span> 2010</span>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Programming+with+C+Blocks+on+Apple+Devices&amp;rft.date=2010-07-07&amp;rft.aulast=Bengtsson&amp;rft.aufirst=Joachim&amp;rft_id=http%3A%2F%2Fthirdcog.eu%2Fpwcblocks%2F&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></span> </li> <li id="cite_note-24"><span class="mw-cite-backlink"><b><a href="#cite_ref-24">^</a></b></span> <span class="reference-text">Full documentation can be found at <a rel="nofollow" class="external free" href="http://docwiki.embarcadero.com/RADStudio/Rio/en/Closure">http://docwiki.embarcadero.com/RADStudio/Rio/en/Closure</a></span> </li> </ol></div> <div class="mw-heading mw-heading2"><h2 id="External_links">External links</h2><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Closure_(computer_programming)&amp;action=edit&amp;section=25" title="Edit section: External links"><span>edit</span></a><span class="mw-editsection-bracket">]</span></span></div> <ul><li><a rel="nofollow" class="external text" href="https://web.archive.org/web/20160510140804/http://library.readscheme.org/page1.html">Original "Lambda Papers"</a>: A classic series of papers by <a href="/wiki/Guy_L._Steele_Jr." title="Guy L. Steele Jr.">Guy L. Steele Jr.</a> and <a href="/wiki/Gerald_Jay_Sussman" title="Gerald Jay Sussman">Gerald Jay Sussman</a> discussing, among other things, the versatility of closures in the context of Scheme (where they appear as <i><a href="/wiki/Lambda_calculus" title="Lambda calculus">lambda</a> expressions</i>).</li> <li><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFGafter2007" class="citation web cs1">Gafter, Neal (28 January 2007). <a rel="nofollow" class="external text" href="http://gafter.blogspot.com/2007/01/definition-of-closures.html">"A Definition of Closures"</a>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=A+Definition+of+Closures&amp;rft.date=2007-01-28&amp;rft.aulast=Gafter&amp;rft.aufirst=Neal&amp;rft_id=http%3A%2F%2Fgafter.blogspot.com%2F2007%2F01%2Fdefinition-of-closures.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></li> <li><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r1238218222"><cite id="CITEREFBrachaGafterGoslingvon_der_Ahé" class="citation web cs1"><a href="/wiki/Gilad_Bracha" title="Gilad Bracha">Bracha, Gilad</a>; Gafter, Neal; <a href="/wiki/James_Gosling" title="James Gosling">Gosling, James</a>; von der Ahé, Peter. <a rel="nofollow" class="external text" href="http://www.javac.info/closures-v05.html">"Closures for the Java Programming Language (v0.5)"</a>.</cite><span title="ctx_ver=Z39.88-2004&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=unknown&amp;rft.btitle=Closures+for+the+Java+Programming+Language+%28v0.5%29&amp;rft.aulast=Bracha&amp;rft.aufirst=Gilad&amp;rft.au=Gafter%2C+Neal&amp;rft.au=Gosling%2C+James&amp;rft.au=von+der+Ah%C3%A9%2C+Peter&amp;rft_id=http%3A%2F%2Fwww.javac.info%2Fclosures-v05.html&amp;rfr_id=info%3Asid%2Fen.wikipedia.org%3AClosure+%28computer+programming%29" class="Z3988"></span></li> <li><a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/Closure.html">Closures</a>: An article about closures in <a href="/wiki/Dynamic_typing" class="mw-redirect" title="Dynamic typing">dynamically typed</a> imperative languages, by <a href="/wiki/Martin_Fowler_(software_engineer)" title="Martin Fowler (software engineer)">Martin Fowler</a>.</li> <li><a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/CollectionClosureMethod.html">Collection closure methods</a>: An example of a technical domain where using closures is convenient, by Martin Fowler.</li></ul> <!-- NewPP limit report Parsed by mw‐web.codfw.main‐f69cdc8f6‐6qhks Cached time: 20241122140523 Cache expiry: 2592000 Reduced expiry: false Complications: [vary‐revision‐sha1, show‐toc] CPU time usage: 0.451 seconds Real time usage: 2.414 seconds Preprocessor visited node count: 2251/1000000 Post‐expand include size: 44079/2097152 bytes Template argument size: 2901/2097152 bytes Highest expansion depth: 12/100 Expensive parser function count: 39/500 Unstrip recursion depth: 1/20 Unstrip post‐expand size: 132992/5000000 bytes Lua time usage: 0.203/10.000 seconds Lua memory usage: 6537164/52428800 bytes Number of Wikibase entities loaded: 0/400 --> <!-- Transclusion expansion time report (%,ms,calls,template) 100.00% 2315.993 1 -total 6.99% 161.868 2 Template:Reflist 4.14% 95.904 1 Template:Short_description 3.28% 75.904 1 Template:Cite_conference 2.87% 66.532 2 Template:Pagetype 1.92% 44.478 14 Template:Cite_web 1.39% 32.116 2 Template:Citation_needed 1.22% 28.320 2 Template:Fix 1.08% 25.111 1 Template:Other_uses 0.76% 17.673 4 Template:Category_handler --> <!-- Saved in parser cache with key enwiki:pcache:idhash:62319-0!canonical and timestamp 20241122140523 and revision id 1246240241. Rendering was triggered because: page-view --> </div><!--esi <esi:include src="/esitest-fa8a495983347898/content" /> --><noscript><img src="https://login.wikimedia.org/wiki/Special:CentralAutoLogin/start?type=1x1" alt="" width="1" height="1" style="border: none; position: absolute;"></noscript> <div class="printfooter" data-nosnippet="">Retrieved from "<a dir="ltr" href="https://en.wikipedia.org/w/index.php?title=Closure_(computer_programming)&amp;oldid=1246240241">https://en.wikipedia.org/w/index.php?title=Closure_(computer_programming)&amp;oldid=1246240241</a>"</div></div> <div id="catlinks" class="catlinks" data-mw="interface"><div id="mw-normal-catlinks" class="mw-normal-catlinks"><a href="/wiki/Help:Category" title="Help:Category">Categories</a>: <ul><li><a href="/wiki/Category:Programming_language_concepts" title="Category:Programming language concepts">Programming language concepts</a></li><li><a href="/wiki/Category:Implementation_of_functional_programming_languages" title="Category:Implementation of functional programming languages">Implementation of functional programming languages</a></li><li><a href="/wiki/Category:Subroutines" title="Category:Subroutines">Subroutines</a></li></ul></div><div id="mw-hidden-catlinks" class="mw-hidden-catlinks mw-hidden-cats-hidden">Hidden categories: <ul><li><a href="/wiki/Category:Articles_with_short_description" title="Category:Articles with short description">Articles with short description</a></li><li><a href="/wiki/Category:Short_description_matches_Wikidata" title="Category:Short description matches Wikidata">Short description matches Wikidata</a></li><li><a href="/wiki/Category:Use_dmy_dates_from_August_2020" title="Category:Use dmy dates from August 2020">Use dmy dates from August 2020</a></li><li><a href="/wiki/Category:All_articles_with_unsourced_statements" title="Category:All articles with unsourced statements">All articles with unsourced statements</a></li><li><a href="/wiki/Category:Articles_with_unsourced_statements_from_December_2014" title="Category:Articles with unsourced statements from December 2014">Articles with unsourced statements from December 2014</a></li><li><a href="/wiki/Category:Articles_with_unsourced_statements_from_September_2011" title="Category:Articles with unsourced statements from September 2011">Articles with unsourced statements from September 2011</a></li><li><a href="/wiki/Category:Articles_with_example_C%2B%2B_code" title="Category:Articles with example C++ code">Articles with example C++ code</a></li><li><a href="/wiki/Category:Articles_with_example_C_Sharp_code" title="Category:Articles with example C Sharp code">Articles with example C Sharp code</a></li><li><a href="/wiki/Category:Articles_with_example_D_code" title="Category:Articles with example D code">Articles with example D code</a></li><li><a href="/wiki/Category:Articles_with_example_Eiffel_code" title="Category:Articles with example Eiffel code">Articles with example Eiffel code</a></li><li><a href="/wiki/Category:Articles_with_example_Haskell_code" title="Category:Articles with example Haskell code">Articles with example Haskell code</a></li><li><a href="/wiki/Category:Articles_with_example_Java_code" title="Category:Articles with example Java code">Articles with example Java code</a></li><li><a href="/wiki/Category:Articles_with_example_JavaScript_code" title="Category:Articles with example JavaScript code">Articles with example JavaScript code</a></li><li><a href="/wiki/Category:Articles_with_example_Objective-C_code" title="Category:Articles with example Objective-C code">Articles with example Objective-C code</a></li><li><a href="/wiki/Category:Articles_with_example_Python_(programming_language)_code" title="Category:Articles with example Python (programming language) code">Articles with example Python (programming language) code</a></li><li><a href="/wiki/Category:Articles_with_example_Ruby_code" title="Category:Articles with example Ruby code">Articles with example Ruby code</a></li><li><a href="/wiki/Category:Articles_with_example_Scheme_(programming_language)_code" title="Category:Articles with example Scheme (programming language) code">Articles with example Scheme (programming language) code</a></li><li><a href="/wiki/Category:Articles_with_example_Smalltalk_code" title="Category:Articles with example Smalltalk code">Articles with example Smalltalk code</a></li></ul></div></div> </div> </main> </div> <div class="mw-footer-container"> <footer id="footer" class="mw-footer" > <ul id="footer-info"> <li id="footer-info-lastmod"> This page was last edited on 17 September 2024, at 19:23<span class="anonymous-show">&#160;(UTC)</span>.</li> <li id="footer-info-copyright">Text is available under the <a href="/wiki/Wikipedia:Text_of_the_Creative_Commons_Attribution-ShareAlike_4.0_International_License" title="Wikipedia:Text of the Creative Commons Attribution-ShareAlike 4.0 International License">Creative Commons Attribution-ShareAlike 4.0 License</a>; additional terms may apply. By using this site, you agree to the <a href="https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Terms_of_Use" class="extiw" title="foundation:Special:MyLanguage/Policy:Terms of Use">Terms of Use</a> and <a href="https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy" class="extiw" title="foundation:Special:MyLanguage/Policy:Privacy policy">Privacy Policy</a>. Wikipedia® is a registered trademark of the <a rel="nofollow" class="external text" href="https://wikimediafoundation.org/">Wikimedia Foundation, Inc.</a>, a non-profit organization.</li> </ul> <ul id="footer-places"> <li id="footer-places-privacy"><a href="https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy">Privacy policy</a></li> <li id="footer-places-about"><a href="/wiki/Wikipedia:About">About Wikipedia</a></li> <li id="footer-places-disclaimers"><a href="/wiki/Wikipedia:General_disclaimer">Disclaimers</a></li> <li id="footer-places-contact"><a href="//en.wikipedia.org/wiki/Wikipedia:Contact_us">Contact Wikipedia</a></li> <li id="footer-places-wm-codeofconduct"><a href="https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Universal_Code_of_Conduct">Code of Conduct</a></li> <li id="footer-places-developers"><a href="https://developer.wikimedia.org">Developers</a></li> <li id="footer-places-statslink"><a href="https://stats.wikimedia.org/#/en.wikipedia.org">Statistics</a></li> <li id="footer-places-cookiestatement"><a href="https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Cookie_statement">Cookie statement</a></li> <li id="footer-places-mobileview"><a href="//en.m.wikipedia.org/w/index.php?title=Closure_(computer_programming)&amp;mobileaction=toggle_view_mobile" class="noprint stopMobileRedirectToggle">Mobile view</a></li> </ul> <ul id="footer-icons" class="noprint"> <li id="footer-copyrightico"><a href="https://wikimediafoundation.org/" class="cdx-button cdx-button--fake-button cdx-button--size-large cdx-button--fake-button--enabled"><img src="/static/images/footer/wikimedia-button.svg" width="84" height="29" alt="Wikimedia Foundation" loading="lazy"></a></li> <li id="footer-poweredbyico"><a href="https://www.mediawiki.org/" class="cdx-button cdx-button--fake-button cdx-button--size-large cdx-button--fake-button--enabled"><img src="/w/resources/assets/poweredby_mediawiki.svg" alt="Powered by MediaWiki" width="88" height="31" loading="lazy"></a></li> </ul> </footer> </div> </div> </div> <div class="vector-settings" id="p-dock-bottom"> <ul></ul> </div><script>(RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgHostname":"mw-web.codfw.main-f69cdc8f6-bklvv","wgBackendResponseTime":171,"wgPageParseReport":{"limitreport":{"cputime":"0.451","walltime":"2.414","ppvisitednodes":{"value":2251,"limit":1000000},"postexpandincludesize":{"value":44079,"limit":2097152},"templateargumentsize":{"value":2901,"limit":2097152},"expansiondepth":{"value":12,"limit":100},"expensivefunctioncount":{"value":39,"limit":500},"unstrip-depth":{"value":1,"limit":20},"unstrip-size":{"value":132992,"limit":5000000},"entityaccesscount":{"value":0,"limit":400},"timingprofile":["100.00% 2315.993 1 -total"," 6.99% 161.868 2 Template:Reflist"," 4.14% 95.904 1 Template:Short_description"," 3.28% 75.904 1 Template:Cite_conference"," 2.87% 66.532 2 Template:Pagetype"," 1.92% 44.478 14 Template:Cite_web"," 1.39% 32.116 2 Template:Citation_needed"," 1.22% 28.320 2 Template:Fix"," 1.08% 25.111 1 Template:Other_uses"," 0.76% 17.673 4 Template:Category_handler"]},"scribunto":{"limitreport-timeusage":{"value":"0.203","limit":"10.000"},"limitreport-memusage":{"value":6537164,"limit":52428800}},"cachereport":{"origin":"mw-web.codfw.main-f69cdc8f6-6qhks","timestamp":"20241122140523","ttl":2592000,"transientcontent":false}}});});</script> <script type="application/ld+json">{"@context":"https:\/\/schema.org","@type":"Article","name":"Closure (computer programming)","url":"https:\/\/en.wikipedia.org\/wiki\/Closure_(computer_programming)","sameAs":"http:\/\/www.wikidata.org\/entity\/Q535335","mainEntity":"http:\/\/www.wikidata.org\/entity\/Q535335","author":{"@type":"Organization","name":"Contributors to Wikimedia projects"},"publisher":{"@type":"Organization","name":"Wikimedia Foundation, Inc.","logo":{"@type":"ImageObject","url":"https:\/\/www.wikimedia.org\/static\/images\/wmf-hor-googpub.png"}},"datePublished":"2002-07-16T03:10:38Z","dateModified":"2024-09-17T19:23:48Z","headline":"technique for creating lexically scoped first class functions"}</script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10