closures

Scala local return?

寵の児 提交于 2019-12-05 12:20:12
I've just discovered that return s in following closure will return from function findPackage def findPackage(name: String, suffix: Option[String] = None): Path = { logger.debug("Looking for package {} with suffix {}", name, suffix) val path: Path = using(Files.newDirectoryStream(appDir)) {dirs => for (val path <- dirs) { val matcher = packagePattern.matcher(path.getFileName.toString) if (matcher.matches() && matcher.group(1).equals(name)) if (suffix.isDefined) { if (matcher.group(2) != null && matcher.group(2).equals(suffix.get)) return path } else return path } throw new

Checking if an RDD element is in another using the map function

对着背影说爱祢 提交于 2019-12-05 10:36:24
问题 I'm new to Spark and was wondering about closures. I have two RDDs, one containing a list of IDs and a values, and the other containing a list of selected IDs. Using a map, I want to increase the value of the element, if the other RDD contains its ID, like so. val ids = sc.parallelize(List(1,2,10,5)) val vals = sc.parallelize(List((1, 0), (2, 0), (3,0), (4,0))) vals.map( v => { if(ids.collect().contains(v._1)){ (v._1, 1) } }) However the job hangs and never completes. What is the proper way

UnboundLocalError: local variable referenced before assignment in python closure

夙愿已清 提交于 2019-12-05 09:47:49
I implemented two simple closures in Python. To me, they looks the same, but one works and the other doesn't. The working one is: def makeInc(x, y): def inc(): return y + x return inc inc5 = makeInc(5, 10) inc10 = makeInc(10, 5) inc5 () # returns 15 inc10() # returns 15 But the second one doesn't work: import os def linker(dest, filename): print filename def link(): if os.path.isfile(filename): # line 17 filename = os.path.join(os.getcwd(), filename) dest = os.path.join(dest, filename) y = rawinput('[y]/n: ln -sf %s %s' % (dest, filename)) if y == 'n': return 1 else: return os.system('ln -sf

How do closures in Perl work?

本小妞迷上赌 提交于 2019-12-05 09:41:25
问题 Newbie in Perl again here, trying to understand closure in Perl. So here's an example of code which I don't understand: sub make_saying { my $salute = shift; my $newfunc = sub { my $target = shift; print "$salute, $target!\n"; }; return $newfunc; # Return a closure } $f = make_saying("Howdy"); # Create a closure $g = make_saying("Greetings"); # Create another closure # Time passes... $f->("world"); $g->("earthlings"); So my questions are: If a variable is assigned to a function, is it

For-loop saving state with closure

坚强是说给别人听的谎言 提交于 2019-12-05 08:15:27
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 reason this isn't doing this. Rather when it is run in terminal, it spits out >>node file.js 1 What am I missing? Could you please elaborate. thefourtheye Because you are returning the value returned by the IIFE immediately, in this statement return (function(e){ console.log(e) })(i); since the IIFE just prints 0 and doesn't return

How can I serialize a closure in Perl?

落爺英雄遲暮 提交于 2019-12-05 08:11:19
I think this might be best asked using an example: use strict; use warnings; use 5.010; use Storable qw(nstore retrieve); local $Storable::Deparse = 1; local $Storable::Eval = 1; sub sub_generator { my ($x) = @_; return sub { my ($y) = @_; return $x + $y; }; } my $sub = sub_generator(1000); say $sub->(1); # gives 1001 nstore( $sub, "/tmp/sub.store" ); $sub = retrieve("/tmp/sub.store"); say $sub->(1); # gives 1 When I dump /tmp/sub.store I see: $VAR1 = sub { package Storable; use warnings; use strict 'refs'; my($y) = @_; return $x + $y; } But $x is never defined in this sub. I would expect that

Why use a closure for assignment instead of directly assigning a value to a key?

本秂侑毒 提交于 2019-12-05 08:09:32
I was watching this video and at 7:10 he's adding a db dependency and is using a closure to assign the value. My question is why not just use direct assignment instead, I mean isn't doing this: $container['db'] = $capsule; equivalent to doing this: $container['db'] = function ($container) use ($capsule) { return $capsule; } If not, what is the difference and which way is better? TLDR it's because defining dependencies as closures makes it possible for dependency injection container to build them on demand, hence you don't need to worry about their order of definition and managing their

Calling closures from an array in Rust

[亡魂溺海] 提交于 2019-12-05 07:45:04
How do I iterate over an array of closures, calling each one in turn? With functions, I discovered I could do this by just iterating over the array, and dereferencing the values that produced: fn square(x: int) -> int { x * x } fn add_one(x: int) -> int { x + 1 } fn main() { let funcs = [square, add_one]; for func in funcs.iter() { println!("{}", (*func)(5i)); } } However, when I try to do the same with closures, I get an error: fn main() { let closures = [|x: int| x * x, |x| x + 1]; for closure in closures.iter() { println!("{}", (*closure)(10i)); } } Produces: <anon>:4:24: 4:34 error:

How safe would it be to use functional-java to add closures to a Java production project?

三世轮回 提交于 2019-12-05 07:23:35
I would love to use closures in Java. I have read that they may or may not make it into Java 7. But an open-source project called functional-java has implemented functional features including closures. How safe would it be to use such a library in an enterprise production app? Is there a better way to add closures to Java currently? Closures will definitely not make it into Java 7, due to a lack of consensus around a single implementation. See here. The Functional Java library is thoroughly tested and actively developed. If you browse the source you will see that it's just simple bog-standard

How to make Groovy / Grails return a List of objects instead of a List of Lists of objects?

假装没事ソ 提交于 2019-12-05 07:20:21
I have a class like this: class Foo { static hasMany = [bars: Bar] } When I write: Foo.getAll() I get a list of Foo objects like this: [ Foo1, Foo2, Foo3 ] When I write: Foo.getAll().bars I get a list of lists of Bar object like this: [ [ Bar1, Bar2 ], [ Bar2, Bar3 ], [ Bar1, Bar4 ] ] But what I want is a unique list of Bar objects like this: [ Bar1, Bar2, Bar3, Bar4 ] My end goal is to have a unique list of ids of the Bar object in the list above, like this: [ 1, 2, 3, 4 ] I have tried variations of the collect method and I have also tried the spread operator but I'm not having any luck. For