Questions tagged [closures]

A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.

Filter by
Sorted by
Tagged with
1 vote
2 answers
43 views

Is there a way to create a closure that computes an nth degree polynomial with random coefficients in Rust?

So the idea is to have a function that returns a closure of degree n with random coefficients. This might be useful for comparing root finding methods, as we can automate the creation of a function to ...
BananaPotatoPower's user avatar
3 votes
1 answer
36 views

Why invoke an inline function immediately, rather than just calling its contained function?

When assigning value to a struct field. FlagSet: (func() *flag.FlagSet { fs := newFlagSet("configure") return fs })(), I think it's equivelent to just calling ...
user2417369's user avatar
-1 votes
0 answers
21 views

Closures in MSIL (CIL) intermediate language

I am interested to learn how closures are implemented in MSIL. The very concept of closure is familiar to me, of course, but I'm not well versed in intermediate languages and bytecodes. I would like ...
programmer999's user avatar
0 votes
0 answers
3 views

Error when using the clo() function in the compositions library

I am getting the following error, when I want to use the clo function in the compositions library: Constrained linear ordination is fitted with the function 'rrvglm' Examples (from the help package): ...
Jose Luis Iparraguirre D'Elia's user avatar
-1 votes
0 answers
30 views

Understanding Environment Records and Execution Contexts in ECMAScript

I've been reading the ECMAScript specification and came across the concept of "Environment Records" and their role in executable code and execution contexts. The documentation outlines that ...
can temizyurek's user avatar
0 votes
0 answers
11 views

How to implement inheritance with closure in Javascript

I am being asked to implement JS inheritance with closure. I have the following code. function CreateUser(name, age) { let sharedFunctionalities = { sayName() { ...
kbl's user avatar
  • 119
0 votes
1 answer
26 views

Doing scopes & closures in JS [duplicate]

I wrote a code for scope and closure function fun1(){ let a = 2 function fun2(){ console.log(a) } return fun2 } b = fun1() console.log(b) According to me, I am storing fun1 ...
Abhijeet's user avatar
0 votes
1 answer
18 views

Crash with unwrapping a previously checked optional in a closure

I have a very rare crash, probably involving a perfect timing (with closing the app or entering a background state?) The last line of this code fileprivate static func showNextDialog() { let ...
Dmitry's user avatar
  • 713
0 votes
2 answers
41 views

How can a closure outlive the main function if the entire process ends when main function ends?

I have below code: use std::thread; fn main() { let x: &'static mut [i32; 3] = Box::leak(Box::new([1, 2, 3])); thread::spawn(|| dbg!(&x)); } When I compile it, I get below error: ...
Fajela Tajkiya's user avatar
-3 votes
0 answers
27 views

How does a variable become a closure in JavaScript? [duplicate]

Please have a look at this code: function closure(){ var msg = 'I am learning closure' return function (){ console.log(msg) } } var printMsg = closure() // console.log(...
AnupRoy's user avatar
0 votes
0 answers
35 views

Swift closure parameter with default value nil still returns some value when not passed by the caller? [duplicate]

In this code: @objc func postToken(completion: (()-> Void)? = nil) { someBlock { completion?() } } when added as a call using a selector, like so: let tokenIndicatorGesture = ...
Anton Unt's user avatar
  • 1,835
0 votes
2 answers
40 views

Is it possible to apply a function using `.map()` to every element of a nested vector in Rust?

Is it possible to apply a closure or function to every element of a Vec<Vec<T>> ? Can this be done with .map()? If not, then is there an alternative? I want to convert a Vec<Vec<...
FreelanceConsultant's user avatar
0 votes
1 answer
35 views

Is there an inbuilt "Or" function which can be used in a Rust closure?

I have written the following Rust function, which contains a closure. fn has_a_none_element(&self) -> bool { let elements_is_none = self.elements.iter().flatten().map(...
FreelanceConsultant's user avatar
0 votes
1 answer
27 views

How to express lifetime constraints for closures which take and return references?

I have sketched out an example problem in the Rust playground. For reference, I will provide the full code at the end of this question. I have attempted to write the following function. fn ...
FreelanceConsultant's user avatar
0 votes
1 answer
26 views

Map to a div grid

I am attempting to adapt the following so that 4x4 grid has numbers 1 through n displayed. Each div cell needs an onclick handler. I tried tinkering the last response from Rendering a chart with ...
Tims's user avatar
  • 629
0 votes
1 answer
53 views

Putting a closure into a dictionary

In an iOS app I have a popup button that contains a list of item names that can change. I am trying to make a dictionary of [String : (String)->Void] to store different actions to be performed ...
psb's user avatar
  • 103
0 votes
1 answer
58 views

How to "vectorize" a function in Rust

Suppose that I want to take a function that operates on two elements of a collection and turn it into a function that operates on two collections elementwise. For example, I want to turn a function ...
YEp d's user avatar
  • 179
1 vote
1 answer
47 views

"Cannot convert return expression of type '()' to return type 'String'" compiler error when trying to access returned string from closure

func requestList(completionParameter: @escaping (String) -> String ) { let url = URL(string: "https://www.google.de")! let task = URLSession.shared.dataTask(with: url) { data, ...
Tardik's user avatar
  • 13
-1 votes
0 answers
23 views

Why This for Loop Is not following the constrain which is i<=5? [duplicate]

function x(){ for(var i=1; i<=5; i++){ setTimeout( function(){ console.log(i); }, i * 1000 ); } } x(); so I was ...
Sagar Baryekar's user avatar
1 vote
2 answers
60 views

Why the first code snippet can solve the stale closure and the second one can't?

It feels like there is nothing difference between the first one and the second one. But the first one code snippet can solve the stale closure. So, why the second one can't? I really can't figure it ...
sam liu's user avatar
  • 33
1 vote
1 answer
17 views

React useEffect cleanup function to save state to a database without running into closure probelms

I understand that this is an issue of closures. I have state in a reducer in my component, which, upon unmount, I would like to save to a database. const [localState, dispatch] = useReducer(myReducer, ...
Brett Buchanan's user avatar
1 vote
1 answer
26 views

JavaScript Closures and Block-Scoped Variables In Loop Memory Management

This question is a few different (I think related) questions, which I give below, but broadly I am trying to understand a code piece from David Flanagan's O'Reilly book on JavaScript that gives an ...
mishar's user avatar
  • 369
0 votes
0 answers
23 views

JS method and closure [duplicate]

Does closure apply to object's methods in JS? I am new to JS. In the following code I deduce that objects do not create scope and methods remember their lexical environment, even though they are ...
kbl's user avatar
  • 119
0 votes
0 answers
29 views

React: Slate state value in a custom hook

I have a custom react hook useSearchAllLocations() like below returning a method fetchLocations() export const useSearchAllLocations = (isFilterSelected = false) => { console.log('Outer ...
Abhinandan Khilari's user avatar
-1 votes
1 answer
45 views

Closure inside another closure is escaping or non-escaping

func perform(_ clsr: () -> Void) { let anotherClosure = { clsr() } } The above code gets compiled but when changing the anotherClosure to var, the compiler gives the error: ...
itsAj's user avatar
  • 1
0 votes
0 answers
30 views

PayPalButtons callback function gets stale data

I have the following code which is an Order component with a paypal button: const Order = () => { const { order } = useOrderData(); console.log("order (1):", order) const ...
Ruben Lemiengre's user avatar
0 votes
1 answer
28 views

Error combining an element and an array in Swift Array Extension - Works in Xcode but not in LeetCode

I've been trying to implement a function inside an Array extension in Swift that returns all the permutations of an array. When I run this code in Xcode, it seems to work just fine. However, when I ...
Kang's user avatar
  • 49
0 votes
0 answers
16 views

How do I track explicit states for ode solvers?

In my derivative function, I have a list of derivatives dy/dt that depend on values at the current timestep. However, I have some intermediate states as well that contribute to this derivative. For ...
lee's user avatar
  • 740
3 votes
1 answer
35 views

Self contained seeding of RNG in a function closure

Is there a way to set a 'localised' seed so that usage of the random number generator within a closure only depends on this seed? For example tmp_fn_test_seed <- function(seed) { set.seed(...
Alex's user avatar
  • 15.2k
0 votes
1 answer
55 views

How to use an async closure in Rust's retry

I have to retry an async function- handle_message & I'm using the retry crate for it (version "1.2.1"). But the second argument is a closure. use retry::{retry, delay::Fixed}; retry(...
NewToCode's user avatar
  • 174
-2 votes
2 answers
40 views

Javasript closure stange behaviour

emphasized textHi I'm learning Javascripts closures and tjis code beahves funny to me: function Unique_id2() { let counter = 0; function f() { return counter++; }; return f(); } ...
Luca's user avatar
  • 1,668
-1 votes
1 answer
54 views

When do you declare variables in anonymous functions in Golang?

I use some anonymous functions in my code and I’m trying to understand the difference (if there is one) between these two code snipets being called in a function: defer func(s *Service, ID string) { ...
Greg T. Wallace's user avatar
1 vote
0 answers
33 views

PHP: Write anonymous function to file for later use

Let's assume, we have an array with anonymous functions as values. It has following contents: $fpool = [ 'f1' => function($a){ if($a > 0){ return [$a*$a, $a+$a]; }...
user2624744's user avatar
0 votes
0 answers
6 views

terminology: does "closure" refer more to definition or to instance?

motivating example in python, though this is not python-specific. def make_foo(x): def foo(y): return x + y def make_bar(x): def bar(y): return x - y f = make_foo(1) b1 = make_bar(1) b2 =...
ajp's user avatar
  • 1,767
0 votes
0 answers
22 views

How to convert a string into a variable in Javascript [duplicate]

My program is when all the three cells have been clicked, all the color of the cell will be appeared in green. In my Javascript program, there is a code line "countx = 1", the idea is to ...
eric2023's user avatar
1 vote
2 answers
44 views

Using closure with event arguments in typescript React

I'm trying to implement a debounce function using closure with typescript React. The problem is that it seems it's made a new reference of the function every time when I try to pass an event argument. ...
Ikhyeon Kim's user avatar
2 votes
1 answer
47 views

Rust empty explicit generic argument for Option<impl Fn(i64)> [duplicate]

I have Option<impl Fn(i64) -> i64> as an argument to a function apply() and I want to pass None value. apply(None). How do I write the apply(None) function call correctly so it compiles? fn ...
Bitcoin Eagle's user avatar
0 votes
1 answer
20 views

In Dart, what's the difference between setting a `lambda` as part of a constructor or setting a normal class

I've seen this kind of stuff when constructing a class: class A { A(this.attr) final String Function() attr; } main() { final myStringAttr = 'some-string'; final a = A(()=> ...
Carlos Daniel's user avatar
1 vote
1 answer
23 views

How to handle lifetimes in closures combined with closures as params and return types?

I've tried writing a closure that receives a closure (let's call it A) that returns a closure that receives a value and then applies closure A to it. Sample: let do_some = |f: &dyn Fn(u32) -> ...
andreihondrari's user avatar
0 votes
0 answers
34 views

Get different values in function and outside a function REACT.JS

I just started my career as a software developer. I have a problem with getting the right values. I have a component, where I get from the parent component as a prop an image tag. In the Child ...
Tech Kam's user avatar
1 vote
1 answer
49 views

when to use def - groovy shell

I'm new to nextflow which uses groovy heavily. I'm learning groovy to learn closures so that can be learned and implemented in nextflow. I've a small piece of code, which I'm trying to print and ...
Death Metal's user avatar
-1 votes
1 answer
86 views

Rust no two closures, even if identical, have the same type [duplicate]

How do to put two closures with the same definition into a Vec? Here is a minimal reproducible example: fn main() { let mut vec = Vec::new(); vec.push(Box::new(|| println!("test"))); ...
Preston's user avatar
  • 180
0 votes
0 answers
37 views

rx in (tx,rx) mpsc::channel in rust gets dropped in thread closure

Would appreciate some help/advice; I am trying to send signals to the gpio pins of the raspberry pi. Sending the signal to the gpio pins is straightford, but stopping a signal running in a loop in a ...
Paul Clements's user avatar
0 votes
1 answer
40 views

Is there a performance penalty for creating a closure vs writing a function in swift?

Is there a performance penalty for creating and using a closure vs a normal function? See example below: using a closure: let array = [1, 2, 3] let doubler: (Int) -> Int = { $0 * 2 } array.map {...
serotonino's user avatar
1 vote
1 answer
36 views

std mpsc sender channel closed when used in closure

I'm trying to create a thread watching for file changes in rust. I'm using the notify crate to get file change events. The following code shows what is run in the watch thread: use std::{path::PathBuf,...
tobi1805's user avatar
  • 171
0 votes
1 answer
68 views

Why do I get a lifetime error when I store closure as a variable and no error when I declare it as an expression?

I'm using the AWS Lambda (via the lambda_http crate) and the following code doesn't compile: let handler = service_fn(move |event: Request| async { handler_organization_post(&shared_client, ...
Howard Dierking's user avatar
0 votes
2 answers
150 views

rust "borrowed data escapes outside of method" with closure

The system here is: event: a trait to be "extended" for different types of events window: controller responsible for window creation and propagating its events further up the queue ...
Vladislav's user avatar
0 votes
0 answers
18 views

Trying to filter a DataSet in R: Error: object of type 'closure' is not subsettable

Veeery basic question where I found no matching answer in other Topics. I read about problems as data.frames and functions...doesn't seem to apply here? I'd like to filter in a specific csv-dataSet(...
Bralor's user avatar
  • 11
1 vote
2 answers
62 views

How to create dynamic block in powershell, that calls script functions?

I'm trying to generate a dynamic UI. I haven't been able to add an OnClick event dynamically. Here's a sample function Say-Hello { Param ( [Parameter(Mandatory=$true)] [...
tamir's user avatar
  • 81
0 votes
1 answer
40 views

Save a list of functions in Python

I have written the following code in Python where the intent is to make a list of every possible boolean function which takes arguments from the set var_set. So for instance if var_set is {"P&...
Addem's user avatar
  • 3,653

1
2 3 4 5
179