How to resolve the algorithm Closures/Value capture step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm Closures/Value capture step by step in the R programming language

Table of Contents

Problem Statement

Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.

Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Closures/Value capture step by step in the R programming language

Source code in the r programming language

# assign 's' a list of ten functions 
s <- sapply (1:10,  # integers 1..10 become argument 'x' below 
    function (x) {
        x  # force evaluation of promise x
	function (i=x) i*i   # this *function* is the return value
    })

s[[5]]()  # call the fifth function in the list of returned functions 
[1] 25    # returns vector of length 1 with the value 25


s[[5]](10) 
[1] 100


s <- sapply (1:10,  
    function (x) {
        x  # force evaluation of promise x
	function () {   
            R <- x*x 
            # evaluate the language expression "x <- x + 1" in the persistent parent environment 
            evalq (x <- x + 1, parent.env(environment()))
            R  # return squared value 
    }})

s[[5]]() 
[1] 25     # 5^2
s[[5]]() 
[1] 36     # now 6^2
s[[1]]()
[1] 1      # 1^2
s[[1]]()
[1] 4      # now 2^2


    evalq (x <- x + 1, parent.env(environment()))


    x <<- x + 1


  

You may also check:How to resolve the algorithm Substitution cipher step by step in the D programming language
You may also check:How to resolve the algorithm First power of 2 that has leading decimal digits of 12 step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Function frequency step by step in the Factor programming language
You may also check:How to resolve the algorithm Jacobsthal numbers step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Quickselect algorithm step by step in the VBA programming language