FAQ Database Discussion Community


JavaScript oop: Designing classes correctly

javascript,oop,closures,prototype
Taking this list of similar questions: How to set up JavaScript namespace and classes properly Javascript namespace declaration with function-prototype Best OOP approach to these two small JavaScript classes I'd concluded there are two possible ways for implementing classes and instances in JS: using an inner function or using a...

Javascript Module Function vs Global Function Performance

javascript,performance,closures,javascript-module
According to the following article, http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html, Module Functions should perform better than Global Functions because they don't have to walk backwards down the global scope chain to find the function. Functions encapsulated inside a module are in their own private scope, which would theoretically provide a considerable performance increase. I...

What does it mean to “close over” something?

data-structures,closures
I'm trying to understand closures, but literally every definition of a closure that I can find uses the same cryptic and vague phrase: "closes over". What's a closure? "Oh, it's a function that closes over another function." But nowhere can I find a definition of what "closes over" means. Can...

AngularJS Set Value to $scope from Nested Function

javascript,angularjs,scope,angularjs-scope,closures
I'm trying to get a value from a function inside a function: Controller $scope.vm = {}; function myFunc(){ $scope.vm.hello = 'Hello'; function myFunction(){ $scope.vm.world = 'world'; } } myFunc(); View <p>{{vm.hello}} {{vm.world}}</p> Here's my Plunk. How can I get this to display "Hello world"?...

Openlayers 3: Binding click event to several maps using a for loop

jquery,for-loop,closures,openlayers,openlayers-3
I would appreciate a little help. Right now I'm learning Openlayers 3. I want to bind a click event to several map objects within a for loop. When I do it like this, the event is only applied to the last map object within the for loop: for(var i =...

Spark Task not serializable (Case Classes)

scala,hadoop,serialization,apache-spark,closures
Spark throws Task not serializable when I use case class or class/object that extends Serializable inside a closure. object WriteToHbase extends Serializable { def main(args: Array[String]) { val csvRows: RDD[Array[String] = ... val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") val usersRDD = csvRows.map(row => { new UserTable(row(0), row(1), row(2), row(9), row(10), row(11))...

Translate Scheme closure-defining function into Haskell

haskell,recursion,types,scheme,closures
The following procedure, written in Scheme, (define (eat xs) (lambda (x) (if (eq? x 'vomit) (reverse xs) (eat (cons x xs))))) can be called in the following way: > eat #{procedure 9165 eat} > (eat '()) #{procedure 9166 (unnamed in eat)} > ((eat '()) 1) #{procedure 9166 (unnamed in eat)}...

Class declaration cannot close over value 'fulfill' defined in outer scope - Swift 2.0

xcode,swift,closures,promise
I'm trying to convert my app from Swift 1.2 to Swift 2.0 and I'm encountering the following error: class B { func test() -> Promise<A> { return Promise<A> { (fulfill, reject) -> Void in anotherPromise.then { _ -> Void in return fulfill(A()) // Class declaration cannot close over value 'fulfill'...

Closure Completion in For Loop Swift

ios,swift,for-loop,closures
I have a group of objects that all need to be validated. The validation requires the use of a closure. I understand the closure can complete at anytime, so the for loop will have completed prior to all the closures. So putting something like reloadData after the for loop will...

Functions in Lua could store local values between calls?

lua,closures
I'm reading "Programming in Lua" and I don't understand behavior of function in Lua in this piece of code: function newCounter () local i = 0 return function () -- anonymous function i = i + 1 return i end end c1 = newCounter() print(c1()) --> 1 print(c1()) --> 2...

How to declare in Swift a function parameter that is a property name

swift,properties,closures
I want to have a class that can access a specified property in another class at runtime. I am guessing it is possible if I pass a closure or a function in as a parameter. For example: class X { let pointFunction : (Thing) -> (CGPoint) init(pointFunction : (Thing) ->...

Why is the variable returned from a closure always one step behind

ios,swift,closures
In the following code the closure accesses a REST API to call a function on an embedded uC, then read a value from the uC. The problem is that the value returned to the variable "result" below, is always one step behind. Meaning, when I turn on the LED and...

How to Supress implicit return from a closure with Void return type in Swift

swift,return,closures,implicit,completion-block
lets consider we have a closure like: (used as completionHandler) func doSomething (completionHandler : (done : Bool)->Void )->Void { ... completionHandler(true) } now if we want to do something like that : doSomething({ (done : Bool)-> Void var data : NSDictionary = NSDictionary() data.setValue("data1", forKey: "data1") // 1 data.setValue("data2", forKey:...

How to use @autoclosure parameter in async block in Swift?

swift,closures
I would like to call an @autoclosure parameter inside dispatch_async block. func myFunc(@autoclosure condition: () -> Bool) { dispatch_async(dispatch_get_main_queue()) { if condition() { println("Condition is true") } } } I get the following error. Closure use of @noescape parameter may allow it to escape. Is it possible to call @autoclosure...

How do I get the triangle array outside so that I can use it

javascript,arrays,closures
I am storing some ID's to an array. The array is correctly populated, but I am not able to log it outside nor use it. I am slightly confused. Here is my code, JavaScript function storeTriangle() { var triangle = []; return function storePolygons() { for (var i = 0;...

Get data off completionhandler - FBRequestConnection

facebook,swift,ios8,closures
I found a lot of information concerning completionHandlers. However, I don't yet get how to handle it in this case. Maybe you can help me. I'm trying to get a list of all Facebook friends and store it in an array. getFacebookFriends func getFacebookFriends() -> NSMutableArray { var retFriendIDs:NSMutableArray =...

Swift Storyboard Segue Loads Blank View When Called From Closure

osx,swift,storyboard,closures,segue
If I call the segue from the View Controller's viewWillAppear(), the second view loads as expected performSegueWithIdentifier("CompleteSegue", sender: self) But if I perform an async download, and call the segue from inside the success closure, it calls the Segue, runs all the code, and displays the view, but it's completely...

How to capture type of a local variable inside a lamda expression in linq

c#,linq,lambda,closures,abstract-class
I found some duplicate code today and would like to reduce it to one method. In order to do it, I'd like to inject something more abstract into the lambda here: public IEnumerable<AbstractFoo> GetMatchingFoos() { return IEnumerable<AbstractFoo> exactMatchFoo = exactMatchList .Where (d => d is RedFoo); } //Horrifying duplicate code!:...

NSTimer questions (closure, @objc, and etc.)

ios,swift,closures,nstimer
I'm pretty new to swift and I have some questions about swift and even just basic OOP (so if you can, please be specific with your answers, thanks a lot!) So I am making an app that has a timer component and the follow code snippets are from that timer...

How do I create & use a list of callback functions?

closures,rust
In Rust, I'm trying to create a list of callbacks functions to invoke later: use std::vec::Vec; fn add_to_vec<T: FnMut() -> ()>(v: &Vec<Box<FnMut() -> ()>>, f: T) { v.push(Box::new(f)); } fn call_b() { println!("Call b."); } #[test] fn it_works() { let calls: Vec<Box<FnMut() -> ()>> = Vec::new(); add_to_vec(&calls, || { println!("Call...

captureStillImageAsyncronouslyFromConnection - Cannot convert the expression's type

ios,swift,closures,avfoundation
I'm fresh to Swift so I'm still ironing out some of the finer details; I apologize if I'm missing something obvious. I've browsed around and found solutions to similar errors in different method calls, but those answers haven't helped me in figuring out my issue. I make this call captureOutput.captureStillImageAsynchronouslyFromConnection(port)...

Swift weakSelf in closure syntax

ios,swift,closures
I have this code to get JSON: Alamofire.request(.GET, worlds).responseJSON { (request, response, JSON, error) in println(JSON) //weakSelf.serverList = JSON } How to declare weakSelf here? I know it should be unowned in my case, but I can't find correct syntax for this. When I try use [unowned self].serverList instead of...

Closures with shorthand not working

swift,closures
I have this closure here, That checks if the first value is greater than the second and if true returns a Boolean value: var bloco12: (Int, Int -> Bool) -> Bool = { return $1($0) } println(bloco12(32, {$0 > 10})) But I learned that there is another way to simplify...

Nested closures and captured variables

perl,memory-leaks,closures,circular-reference
I have this example with nested closures which demonstrates memory leak use v5.10; use strict; package Awesome; sub new { bless {steps => [], surprise => undef}, shift; } sub say { print "awesome: ", $_[1], "\n"; } sub prepare { my ($self, @steps) = @_; for my $s (@steps)...

How to return a value using a closure and assigning the value to a global variable

php,closures
What I am trying to achieve is to use closure to add the variables present in the array and assigning the result to $mul variable, but it doesn't seem to work. Where have I gone wrong? $array = [1,2,3,4,5]; $mul =1; $sum = function(){ global $mul; foreach($array as $e){ $mul+=...

Is there a standard pattern for verifying an async request is still needed?

multithreading,swift,mobile,closures
In mobile apps apps we can't (or should not) make network requests on the main thread. We normally get the results of the request back via a callback or a closure that is executed on the main thread when the result is available. Since the user may have moved on...

Problems mixing Arrays, Tuples and Closures in Swift [duplicate]

arrays,swift,closures,tuples
This question already has an answer here: Array of tuples in Swift 3 answers I am trying to manage an array of (String, closure) tuples. The array is defined as: var menuItems: [(title: String, closure: () -> Void)] = [] Now I'm trying to add items to it: //...

Odd error when capturing function parameter in Swift call to animateWithDuration:Animations:

swift,closures,animatewithduration
I'm writing some simple animation code to make a button get taller and then shorter using UIView animations. The code is a little long, but fairly simple: func animateButton(aButton: UIButton, step: Int) { let localStep = step - 1 let localButton = aButton let halfHeight = aButton.bounds.height / 2 var...

Why aren't the references to the private var's not being updated?

javascript,class,scope,closures
The add method isn't working like intended. When I have 2 time object t (all 0's), and t2 (1 minute). When I add t2 to t, t doesn't change BUT when I call my toString method on t it gives me the expected value. Here is what I mean if...

JavaScript for loop closure issue

javascript,closures
I am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle. var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ]; var catsArray =...

var functionName vs functionName assignment in a closure

javascript,function,closures,variable-declaration
This closure code would work: function setupSomeGlobals(){ var num = 666; gPrintNumber = function() { // play with var assignment console.log(num) } gIncreaseNumber = function() { num++; } } setupSomeGlobals(); gPrintNumber(); gIncreaseNumber(); gPrintNumber(); Yet, when I place the var keyword in front of the functions within the code, it all...

addEventListener not working properly

javascript,closures,addeventlistener
I am new to JS, currently learning from multiple different sources, this is a simple catclicker game I am building with vanilla js. On line 75 - I have an addeventlistner that is being called even after it's no longer selected. For example, it keeps counting even after the cat...

Python closure confusion

python,closures
I was playing around with closures in Python and I do not understand why the following does not work and how to make it work: >>> def make_counter(): ... i = 0 ... def inner(): ... i += 1 ... return i ... return inner ... >>> c = make_counter()...

Function closures

javascript,function,closures
Hi I'm trying to run the following function: function add (a, b) { return a + b; } var make_lazy = function (add, a, b) { return function () { add(a,b); } } Basically what I'm trying to do is to pass another function as an argument and its parameters...

How to create empty closure properly?

swift,syntax,closures
I have a class with a closure as a property: class MyClass{ var onChange = {} func foo(){ onChange() } } A behaviour implemented in closure is used in method foo: var c = MyClass() c.onChange = { println("something is changed"); } c.foo() // prints 'something is changed' It's easy...

Inject outer scope when monkey-patching instance method in Ruby [duplicate]

ruby,closures,metaprogramming
This question already has an answer here: Is it possible to define a Ruby singleton method using a block? 2 answers I have a container class Foo with a method frob, and I want to add a similarly named method, which will delegate to the container, to each of...

How to efficiently determine the depth of closures

javascript,closures
In terms of closure, if only account for functions that return another function as shown in the following examples. How do we programmatically determine the depth of this closure in runtime? Let's say this function F has the depth of 2: function F(a){ // 1 return function G(b){ // 2...

Weak reference to closure in Swift

swift,closures,weak-references
I have the following code to create an observable property for data binding. It's in the works so I'm not sure what the final implementation is going to be and I'm still pretty new to Swift. class Observable<T> { typealias Observer = T -> Void var value: T { didSet...

Swift parse framework and closures

swift,closures,parse-framework
This is srsly driving me crazy. I am trying to use getFirstObjectInBackgroundWithBlock() method in swift but I can't figure out how to (not) use the optionals .. I just want to get the user's score from the parse server And I do it like this: func updateScoreForCurrentUser(score: Int){ let user...

Issues using closures within future events

javascript,closures
I'm attempting to create a function that captures a number of elements on the page, iterates through them and applies a mousedown event listener, then calls another function and passes it some data in a variable. This variable changes throughout the course of the loop, so I want to utilize...

JavaScript Closure in Loop [duplicate]

javascript,closures
This question already has an answer here: JavaScript closure inside loops – simple practical example 25 answers I wanted to solve this question posted as a public question on testdome. Each as[i] should be a function that does alert(i). The code to be bug-fixed is this: function registerHandlers() {...

How does the closure capture values?

ios,swift,closures
I post a question about closure but it was kept as on hold When to use closures in swift? Now i want to go in detail and being more specific. How does this line work? let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] func backwards(s1: String, s2: String) -> Bool...

Calling closure using ironscheme

c#,closures,ironscheme
We would like to call a scheme closure from C# using IronScheme, but we keep getting an exception, saying "not a pair". We would like to call the following Scheme code: (define (create-robot name) (let* ( (position (cons 0 0)) (move-forward(lambda (x) (set! position (cons (car position) (+ x (cdr...

Pass arguments to inner anonymous function

jquery,wordpress,scope,closures
I try to make a function in WordPress to add customizer color settings with JS. My function is: function customize_color(id,selector,prop){ wp.customize(id, function(value) { value.bind(function(to) { $(selector).css({ prop:to }); }); }) } And I want to call it like this: customize_color('body_background','body','background') With the debugger I notice that inside the function(to) I...

Fixing a closure within a loop

javascript,closures
I'm going through JavaScript: The Definitive Guide by David Flanagan and I am stuck at the following example: window.onload = function() { var elements = document.getElementsByClassName("reveal"); for(var i = 0; i < elements.length; i++) { var elt = elements[i]; var title = elt.getElementsByClassName("handle")[0]; title.onclick = function() { if(elt.className == "reveal")...

Generic fn, channel, and thread spawn

closures,rust,lifetime
I have this code here: (Playground link) use std::thread; use std::sync::mpsc::channel; fn run<T: Send>(task: fn() -> T) -> T { let (tx, rx) = channel(); thread::spawn(move || { tx.send(task()); }); rx.recv().unwrap() } fn main() { let task = || 1 + 2; let result = run(task); println!("{}", result); } But...

Ruby - accessing instance methods / variables from anonymous class

ruby,closures,anonymous-class
I have following Ruby code: class Baz def foo() qux = Class.new() { def call() bar() end }.new() qux.call() end def bar() puts "bar" end end b = Baz.new() b.foo() How can I access method bar from the anonymous class, that means from qux.call? Is it possible? I'm keeping getting...

What is the difference between the below syntaxes of closures in swift

ios,swift,closures,completionhandler
Here is my function declaration with closure func isTextValid(input: String, completion: (result: Bool) -> ()) { if input == "Hello" { completion(result: true) } else { completion(result: false) } } When I am calling the function below like this it doesn't print the right result which is "false", instead...

Access global variable outside of anonymous function in JavaScript using require

javascript,node.js,closures,anonymous-function
I'm developing a HTML5 real-time multiplayer game and I have a game_core.js file that runs the game physics using the p2 library. I would like to run this file both on the client, to make prediction, and on the authoritative server. Here's the constructor and module.exports: function gameCore() { this.world...

Suppress Swift compiler warning

ios,swift,closures,compiler-warnings,suppress-warnings
I'm using the Nimble assertion framework for unit testing in Swift (Xcode 6.3 beta). It works fine, but the compiler gives a warning for one of the lines in the Nimble source code: public func expect<T>(expression: () -> T?, file: String = __FILE__, line: UInt = __LINE__) -> Expectation<T> {...

Using map on NSDictionary

swift,closures,nsdictionary
SETUP I am loading data from my server by using my API The returned data is in JSON The JSON provided by the API is pictured below I use ALAMOFIRE to receive the data from the API and parse the JSON response JSON { data: [ { owner: "FREDL", street:...

How to use closures in nested map?

closures,rust
I am trying to make a 2-dimensional matrix from a functor that creates each element, and store it as a flat Vec (each row concatenated). I used nested map (actually a flat_map and a nested map) to create each row and concatenate it. Here is what I tried: fn make<T,F>(n:...

Closures vs Delegate pattern

ios,swift,delegates,closures
I'm working with network request classes and I'm concerned about crashes. For instance, working with closures is really easy as you pass a callback method to a function: // some network client func executeHttpRequest(#callback: (success: Bool) -> Void) { // http request callback(true) } // View Controller func reload() {...

Closure callbacks in PHP (Laravel 5)

php,closures,laravel-5
I am learning Laravel 5, and getting a little bit confused at these lines of code (creation of service provider): public function register() { $this->app->singleton('Riak\Contracts\Connection', function($app) { return new Connection($app['config']['riak']); }); } I cant understand $app variable, and frome where it will be passed into function? Thanks! P.S. And please...

Sensible approach to callbacks on object prototype methods in javascript/jquery?

javascript,jquery,ajax,closures,prototypal-inheritance
Is what I've done below a sensible approach to allow callbacks to run on functions defined in an object's prototype, such that the scope is correct? I've been wrestling with the correct way to set the value of this when an object's prototype method is the one to run in...

instancetype parameters type in closure/callback for subclasses

swift,closures
Say I have an asynchronous task to grab an array of instances like so: class func fetchListOfInstances(callback: ([MySuperClass])->()) { // do long task asynchronously and call the callback } and this could be used like so: MySubclass.fetchListOfInstances() { myList in // myList inferred as [MySuperClass] for whatever in myList {...

Should every function be a closure?

javascript,node.js,function,closures
Since closures and the ability to call a function later with its closed over variables seems to be a big plus with javascript's capabilities, I'm finding myself constantly using the following construct: var func; func = function (args) {return function (moreArgs) { Do something; };}; Is this normal javascript programing...

hide object property from all objects except one in javascript

javascript,oop,closures
Say i have the code: function Obj(){ var _x = 5; this.getX = function(){ return _x; }; } var obj = new Obj(); function God(){ var x = obj.getX(); // i want 5 here } function Human(){ var x = obj.getX(); // i want error/undefined here } var x =...

Passing parameters to function closure

go,closures
I'm trying to understand the difference in Go between creating an anonymous function which takes a parameter, versus having that function act as a closure. Here is an example of the difference. With parameter: func main() { done := make(chan bool, 1) go func(c chan bool) { time.Sleep(50 * time.Millisecond)...

Javascript Module Using Apply and Returning This

javascript,closures,module-pattern,javascript-module
I have been in constant search for the most simple Javascript module pattern. I have read pretty much every article I can find. Most module patterns like to create an object, add functions to it, then return that object and expose the public methods, like this: var Module = (function()...

Javascript Calling a nested function from within itself

javascript,function,methods,nested,closures
If I run the following... function outer(){ function inner(){ } inner(); } inner will run the first time as expected. If I then try to run the following... function outer(){ function inner(){ inner(); } inner(); } inner will again run the first time as expected, but then fails at any...

Why doesn't Array.sorted() have default closure?

swift,closures
given the following playground fragment let list = [4.2, 1.3, 7.8] let list1 = list.sorted() { $0 < $1 } let list2 = sorted(list) let list3 = sorted(list) { $0 < $1} I can use two forms of the free function sorted, with or without the closure. But there is...

Understanding Python Closures

python,python-2.7,scope,closures
I always thought that Python 2.7 functions refer to the scope they were defined in. Consider the following code. Why is the second output not "calculating: sin"? Is there any way to modify the code so it is working as expected? import math mymath = dict() for fun in ["sin",...

JavaScript Closures and Parentheses

javascript,closures
1. <script type="text/javascript"> var incrementClickCounts = (function(){ var clickCounts = 0; return function() { return ++clickCounts; } })()() </script> <input type="button" value="clickkkk" onclick="alert(incrementClickCounts);" /> 2. <script type="text/javascript"> var incrementClickCounts = (function(){ var clickCounts = 0; return function() { return ++clickCounts; } })() </script> <input type="button" value="clickkkk" onclick="alert(incrementClickCounts());" /> I'm working...

Weird non-lisp errors with capturing labels with a lambda and `reduce`

lambda,crash,closures,common-lisp,allegro-cl
I stumbled across a very weird bug (?) while I was developing an application in Allegro Common Lisp, v9.0 for Windows. I do not get the regular lisp errors, instead I get system errors encapsulated in a lisp condition. I managed to create a simple test-case to reproduce the error...

Dictionary comprehension with lambda expression fails to produce desired result [duplicate]

python,dictionary,lambda,closures,dictionary-comprehension
This question already has an answer here: Python lambda closure scoping 1 answer I'm creating a one liner to map the string of int to a function testing if the values are matched. Ideally, the result dictionary d behaves like d['0'](0) is True and d['0'](1) is False. But instead,...

Using lambda and closure together in PHP

php,lambda,closures
I am trying to understand the use of these two lambda and closure function. But can't understand it properly. It would be great if i could understand it with illustration and details. $array = array(12345, 'abcde'); $lambda = function($value) { return md5($value); }; $closure = function($value) use ($lambda) { return...

Reflexive Transitive Closure in Alloy in Ternary Operator

closures,alloy
I have an alloy model sig BinaryTree{ root : Node, nodes: set Node, left, right : Node -> Node } Now, I have a predicate defined over it, which is valid syntax pred Connected[t: BinaryTree, l:Node -> Node, r: Node -> Node] { all n: t.nodes | n in t.root.*(l+r)...

JavaScript Closure Callback Itself

javascript,jquery,callback,closures
Here is the closure I wrote: var slider = (function(){ var count = 3; return function(){ if (count>0) { $("#message").html("<h1>"+count+"</h1>"); count--; $("#message").removeClass("animated zoomIn"); $("#message").addClass("animated zoomIn"); $("#message").one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function(){ return slider(); }()); } else{ showCube(); } }() }); This closure gets executed by a jquery plugin: $("#fishes").addClass("animated slideOutLeft").one("webkitAnimationEnd...

How to have an optional trailing closure?

swift,closures
I'm trying to write a function that I can call with trailing closure syntax like so: func hello( message: String, closure: (( msg: String ) -> Void)?) { println( "called hello with: \(message)" ); closure?( msg: message ); } I would expect to be able to call this function with...

Loop closure - Where do I put it?

javascript,arrays,json,closures
In relation to a previous post, I am having a hard time figuring out where to put a loop closure for an array I am using to match against JSON returns. Below is my revised code: $(function() { var $reports = $('#repOut'); var techCount = 0; var repCount = 0;...

What is the correct way to wrap Angularjs code in a closure?

javascript,angularjs,closures
I have a simple application outlined in this question: Angular scope not affecting ng-show as expected Which exposes my application via global variables, this is obviously not ideal. I have tried wrapping the Angularjs code in a closure but I get errors in the browser telling me that the objects...

How can closures access destructed variables?

javascript,oop,closures
while I was learning ways to create Objects I found Durable Constructor Pattern which depends on closures and the way to create private variables. so for example: function Person(name, age, job){ var o = new Object(); o.sayName = function(){ alert(name); }; return o; } var m = new Person('joe',20, 'anything');...

For-loop saving state with closure

javascript,node.js,for-loop,closures
Forgive me if this might be a bit of a noobie question, but this should work shouldn't it? var elems = [1,2,3,4,5] for (var i = 0; i <elems.length; i++) { return (function(e){ console.log(e) })(i); } Meaning, it should spit out >>node file.js 1 2 3 4 5 For some...

dispatch_group_leave crash in swift

ios,swift,closures,health-kit
This happens very rarely. Here is the last line of the stack trace: 0 libdispatch.dylib 0x0000000197a85a9c dispatch_group_leave + 48 dispatch_group_leave is called in a complete closure which is invoked like this: dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let query = HKStatisticsCollectionQuery(quantityType: quantityType, quantitySamplePredicate: nil, options: statisticOptions, anchorDate: anchorDate,...

state retention for classes and closures

python,closures
source: Learning python by mark lutz area of content:page #503 classes versus closures: It states that " classes may seem better at state retention because they make their memory more explicit with attribute assignments. closure functions often provide a lighter-weight and viable alternative when retaining state is the only goal....

Reusing closures in Swift

swift,closures
Which of the following is better: Sample1: var x: Int = 0 for _ in 1...5 { someList.append( Foobar(someClosure: { println("X = \(x)") })) } Sample2: var x: Int = 0 var c: ()->() = { println("X = \(x)") } for _ in 1...5 { someList.append( Foobar(someClosure: c)) } If...

Swift creates instance of wrong type when using a generic function with a closure

swift,generics,closures
I'm trying to create a generic function that take a closure as a parameter. I'm having an issue though, so to isolate the problem, I've created the following code that can be run in a playground. class BaseClass { init(message: String) { println("Base class says: " + message) } func...

Is there any difference between closure in Scheme and usual closure in other languages?

functional-programming,scheme,closures,sicp
I'm studying SICP right now. And I found the definition of closure in SICP is (maybe) different from closure definition in other languages. Here's what SICP says: The ability to create pairs whose elements are pairs is the essence of list structure's importance as a representational tool. We refer to...

Mutating an upvar captured by value in a FnMut closure

closures,rust
I am attempting to create a simple program, with a closure containing a collection that progressively empties itself: fn main() { let vector = vec![1, 2, 3]; let mut allow_once = move |i: &i32| -> bool { if let Some(index) = vector.position_elem(i) { vector.remove(index); return true } false }; for...

'Cannot convert the expression's type' with optional in closure body

swift,closures,optional
I have come across (most definitely) a feature that I don't quite understand. I have a closure, that takes in a Float and has no return value, aka (number: Float) -> Void. In that closure, I perform a call on optional value, not forcing its unwrapping, because I like the...

JavaScript changing variables inside an object [duplicate]

javascript,closures
This question already has an answer here: How to access the correct `this` / context inside a callback? 4 answers var tempOut = false; var foo = function () { this.tempIn = false; this.counter = function () { setTimeout(function () { this.tempIn = true; tempOut = true; },5000); };...

Swift/iOS SDK: Generic Function with Class Type/Name Closure/Block Issue

ios,swift,generics,closures
I'm trying to write a generic class, that takes a custom class name and creates an instance of that class name. Before and after creation I do some generic stuff that applies to all classes. I want to add some parameters to the instance that are class specific. That's why...

Javascript module pattern and global variable

javascript,closures
Seems simple enough, but I cannot get it to work: // Demonstrative only, how can I access canvas from rotate? _imagePreview = function() { var canvas = ''; return { load: function() { fileReader.onload = function(e) { image = new Image(); image.onload = function() { // Empty string (expected) console.log(this.canvas);...

How to access String in Closure

javascript,jquery,jquery-mobile,closures,concat
by triggering xyEvent I want to concatenate a string. But myClosure() is always empty. Why? Thanks for help. first.js: $(document).ready(function () { $("#...").on("tap", function () { myClosure(new Item()); }); ... } second.js var string; xyEvent { string = "hello" + myClosure(); // here is the problem }); var myClosure =...

Print alert() with proper values

javascript,closures
I was testing closures in Fiddle. The following piece of code prints all the i values from 0-9 but in random order. for (var i = 0; i < 10; i++) { (function (i) { setTimeout(function () { alert(i); }, 2000); })(i); } How do I overcome this problem, that...

writing a wrapper for a linear modeling function [MASS::lm.gls()]

r,closures,wrapper,linear-regression
The function MASS::lm.gls fits a linear model using generalized least squares, and returns an object of class "lm.gls", but is has no print, summary or other methods. I could define these simply by hijacking the methods for "lm" objects print.lm.gls <- function(object, ...) { class(object) <- "lm" print(object, ...) }...

What's the difference between filter(|x|) and filter(|&x|)?

closures,rust
In the Rust Book there is an example of calling filter() on an iterator: for i in (1..100).filter(|&x| x % 2 == 0) { println!("{}", i); } There is an explanation below but I'm having trouble understanding it: This will print all of the even numbers between one and a...

Javascript, how return functions in closures are concatenated with the outer function

javascript,closures
function func() { return this == myObject; } var boundFunc = func.bind(myObject, "arg1", "arg2"); boundFunc("arg3", "arg4"); Function.prototype.bind = function() { var fn = this; var args = Array.prototype.slice.call(arguments); var object = args.shift(); return function() { var allArgs = args.concat(Array.prototype.slice.call(arguments)) return fn.apply(object, allArgs); }; } I need some help with the...

Is Java's Lambda equivalent to Objective-C Blocks? [closed]

objective-c,lambda,closures,objective-c-blocks
I noticied that Java's Lambda expressions seem equivalent to Objective-C blocks. Are Java's Lambda expressions exactly equivalent to Objective-C's Blocks? If not, what make's Objective-C blocks different?...

Passing multiple arguments to curried functions

javascript,function,arguments,closures,currying
I'm currently reading the book, Effective Javascript and have reached the chapter regarding closures. There's an example that illustrates how to pass the argument of a nested function as so: function sandwichMaker(magicIngredient) { function make(filling) { return magicIngredient + " and " + filling; } return make; } var hamAnd...

Is it true that every function in JavaScript is a closure?

javascript,closures,ecmascript-5
I understand that every function in JavaScript is a first-class object and it has an internal property [[scope]] which hosts the binding records of the function's free variables. However, there are two special cases. Is the function created by Function constructor also a closure? The function object created by Function...

Local dynamic binding in common lisp

closures,common-lisp,dynamic-binding
Honnestly, I'm not sure I fully understand what it means for a binding to be "dynamic" versus "lexical". But I understand that when I use defvar or defparameterto define a binding, 1. it declares a global variable 2. the binding is declared "special", so that it can be shadowed by...

Timeout with bind, call & apply methods

javascript,closures,this,settimeout,iife
Up until now, I've always used var self = this before creating a function that would need access to its parent. However the bind() method seems like a more appropriate way to do so and I'm exploring that option, along with the apply() and call() methods. This is what I...

Is there any possibilities to call the f1() function from outside of the closure in javascripot

javascript,function,closures
function mainFunc(){ function f1(){ alert("f1"); } function f2(){ alert("f2"); } } function myFun(){ var data = f1(); } Is there any possibilities to call the f1() function from outside of the closure in javascript....

Groovy's inconsistent destructuring / decomposition on lists?

groovy,closures,decomposition,destructuring
Positive Case: Can get into a list groovy> println GroovySystem.version groovy> final data1 = [[99,2] , [100,4]] groovy> data1.collect{x,y->x+y} 2.2.1 Result: [101, 104] Negative Case: Can not do the same groovy> println GroovySystem.version groovy> final data = [x:[99,2] , y:[100,4]] groovy> data.collect{key, val-> groovy> val.collect{x,y->x+y} groovy> }.flatten() 2.2.1 Exception thrown...

Swift closures [weak self] and async tasks

ios,swift,asynchronous,closures
Imagine a situation, when you want to asynchronously load some text from the server and display the result in the ViewController's UITextField. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { //... some long running async operation if let textResponse = responseFromServer { dispatch_async(dispatch_get_main_queue(), { [weak self] () in self?.textField.text = textResponse }) } }) A.)...

Passing property type as parameter

swift,closures
Is there a way to pass the property to a function as a parameter ? class Car { let doors : Int = 4 let price : Int = 1000 } Is there a way to pass the Car property as a type to a function ? I would like...

How to pass a function in another function with variadic arguments with javascript? [duplicate]

javascript,function,closures,pass-by-reference
This question already has an answer here: Calling dynamic function with dynamic parameters in Javascript 9 answers I have a pre-process function, here's an example function function preprocess (msg, fct) { alert(msg); fct(???); } I need to execute the function fct in the preprocess function, but fct not always...

Python for loop iteration using lists

python,list,for-loop,graph,closures
closur=[] i=6 dis_tn=distance[i] headnode=x for k in headers[headnode]: if distance[k]<=dis_tn: if i in headers[k]: closur.append(x) closur.append(k) closur.append(i) else: #break headnode=k continue print "Closure of (",x,",",i,")= ",closur In the above given code, in the else part, i need headnode=k and in the next iteration, the for loop needs to take the...