Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Scheme (programming language)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Delayed evaluation=== {{See also|Lazy evaluation}} Scheme supports delayed evaluation through the <code>delay</code> form and the procedure <code>force</code>. <syntaxhighlight lang="Scheme">(define a 10) (define eval-aplus2 (delay (+ a 2))) (set! a 20) (force eval-aplus2) ===> 22 (define eval-aplus50 (delay (+ a 50))) (let ((a 8)) (force eval-aplus50)) ===> 70 (set! a 100) (force eval-aplus2) ===> 22 </syntaxhighlight> The lexical context of the original definition of the promise is preserved, and its value is also preserved after the first use of <code>force</code>. The promise is only ever evaluated once. These primitives, which produce or handle values known as [[Futures and promises|promises]], can be used to implement advanced [[lazy evaluation]] constructs such as [[stream (computing)|stream]]s.<ref name="srfi-41">{{Cite web |last=Philip L. Bewig |date=2008-01-24 |title=SRFI 41: Streams |url=http://srfi.schemers.org/srfi-41/srfi-41.html |access-date=2012-08-09 |publisher=The SRFI Editors, schemers.org}}</ref> In the R6RS standard, these are no longer primitives, but instead, are provided as part of the R5RS compatibility library (rnrs r5rs (6)). In R5RS, a suggested implementation of <code>delay</code> and <code>force</code> is given, implementing the promise as a procedure with no arguments (a [[thunk]]) and using [[memoization]] to ensure that it is only ever evaluated once, irrespective of the number of times <code>force</code> is called (R5RS sec. 6.4).<ref name="r5rs"/> SRFI 41 enables the expression of both finite and infinite sequences with extraordinary economy. For example, this is a definition of the [[Fibonacci sequence]] using the functions defined in SRFI 41:<ref name="srfi-41"/> <syntaxhighlight lang="Scheme"> ;; Define the Fibonacci sequence: (define fibs (stream-cons 0 (stream-cons 1 (stream-map + fibs (stream-cdr fibs))))) ;; Compute the hundredth number in the sequence: (stream-ref fibs 99) ===> 218922995834555169026 </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)