lambda,crash,closures,common-lisp,allegro-cl , Weird non-lisp errors with capturing labels with a lambda and `reduce`

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


Tag: 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 (it's very silly):

(defun lambda-producer ()
  (labels ((producer-label (x y)
                           (if (> x y) (- x y) (- y x)))
           (producer-label2 (x y)
                            (max (producer-label x 2) (producer-label y 3))))
  (lambda (x)
    (reduce (lambda (a b) (producer-label2 a b)) x))))

;; Get errors when calling:
(funcall (lambda-producer) (list 2 1 5 12))

I get a Stack overflow error for this test case every time I try it.

In my original code I got a plethora of errors, mostly segmentation faults, once a 'can not take car of <..> because it is not listp' and once Allegro crashed.

When running the same snippet (or my original code) in CLisp, everything runs fine and the REPL gives an answer.

My question: Am I doing something wrong or illegal here, or is there a bug in Allegro CL? If so, can we determine what that bug is and what to do about it?

Some experimentation seems to indicate that the reduce and double labels are essential in reproducing the error; replacing reduce with a funcall or if there is only one label does not give an error.


This is a compiler bug. Please contact Franz.

CG-USER(8): (disassemble (lambda-producer))
;; disassembly of #<Closure Template Function (:INTERNAL LAMBDA-PRODUCER 0)>
;; formals: X
;; closure vectors:
;;      0: #<Closure (LABELS LAMBDA-PRODUCER PRODUCER-LABEL2) @ #xdfdda7a>
;; constant vector:
0: #<Closure Template Function (:INTERNAL (:INTERNAL LAMBDA-PRODUCER 0) 0)>

;; code start: #x21869018:
   0: 55          pushl ebp
   1: 89 e5     movl    ebp,esp
   3: 83 ec 38  subl    esp,$56
   6: 89 75 fc  movl    [ebp-4],esi
   9: 89 5d e4  movl    [ebp-28],ebx
  12: 39 63 1a  cmpl    [ebx+26],esp
  15: 76 03     jbe 20
  17: ff 57 43  call    *[edi+67]      ; SYS::TRAP-STACK-OVFL
  20: 83 f9 01  cmpl    ecx,$1
  23: 74 03     jz  28
  25: ff 57 8b  call    *[edi-117]    ; SYS::TRAP-WNAERR
  28: 8b 5d 00  movl    ebx,[ebp+0]
  31: 8b 5b ec  movl    ebx,[ebx-20]
  34: 8b 5b fa  movl    ebx,[ebx-6]
  37: 80 7f cb 00 cmpb  [edi-53],$0        ; SYS::C_INTERRUPT-PENDING
  41: 74 03     jz  46
  43: ff 57 87  call    *[edi-121]    ; SYS::TRAP-SIGNAL-HIT
  46: 8b 56 12  movl    edx,[esi+18] ; #<Closure Template Function (:INTERNAL (:INTERNAL LAMBDA-PRODUCER 0) 0)>
  49: ff b7 43 fe pushl [edi-445] ; SYS::CLOSURE-HEADER
      ff ff 
  55: 8f 45 d0  popl    [ebp-48]
  58: ff b7 47 fe pushl [edi-441] ; SYS::CLOSURE-ADDRESS
      ff ff 
  64: 8f 45 d4  popl    [ebp-44]
  67: 89 55 d8  movl    [ebp-40],edx
  70: 89 5d dc  movl    [ebp-36],ebx
  73: 8d 5d e2  leal    ebx,[ebp-30]
  76: 89 c2     movl    edx,eax
  78: 89 d8     movl    eax,ebx
  80: 8b 5e 16  movl    ebx,[esi+22] ; REDUCE
  83: ff 57 27  call    *[edi+39]      ; SYS::TRAMP-TWO
  86: 89 7d f0  movl    [ebp-16],edi
  89: c9          leave
  90: 8b 75 fc  movl    esi,[ebp-4]
  93: c3          ret

;; disassembly of #<Closure Template Function (:INTERNAL (:INTERNAL LAMBDA-PRODUCER 0) 0)>
;; formals: A B

;; code start: #x2186ccc0:
   0: 55          pushl ebp
   1: 89 e5     movl    ebp,esp
   3: 83 ec 30  subl    esp,$48
   6: 89 75 fc  movl    [ebp-4],esi
   9: 89 5d e4  movl    [ebp-28],ebx
  12: 39 63 1a  cmpl    [ebx+26],esp
  15: 76 03     jbe 20
  17: ff 57 43  call    *[edi+67]      ; SYS::TRAP-STACK-OVFL
  20: 83 f9 02  cmpl    ecx,$2
  23: 74 03     jz  28
  25: ff 57 8b  call    *[edi-117]    ; SYS::TRAP-WNAERR
  28: 8b 5d 00  movl    ebx,[ebp+0]
  31: 8b 5b ec  movl    ebx,[ebx-20]
  34: 8b 5b fa  movl    ebx,[ebx-6]
  37: 80 7f cb 00 cmpb  [edi-53],$0        ; SYS::C_INTERRUPT-PENDING
  41: 74 03     jz  46
  43: ff 57 87  call    *[edi-121]    ; SYS::TRAP-SIGNAL-HIT
  46: ff 73 f6  pushl   [ebx-10]
  49: 8f 45 dc  popl    [ebp-36]        ; EXCL::|local-0|
  52: 8b 75 dc  movl    esi,[ebp-36] ; EXCL::|local-0|
  55: 89 fb     movl    ebx,edi
  57: b9 02 00 00 movl  ecx,$2
  62: ff 57 23  call    *[edi+35]      ; SYS::FUNCALL-TRAMP
  65: 89 7d f0  movl    [ebp-16],edi
  68: c9          leave
  69: 8b 75 fc  movl    esi,[ebp-4]
  72: c3          ret
  73: 90          nop

At 49 and 52 of the second closure template, you can see that it's feeding itself to sys::funcall-tramp1 with 2 arguments2.

  1. sys::funcall-tramp is an internal that I think might perform or otherwise allow tail calls.

  2. According to ecx at 57, since ecx is what seems to be used to check if the internal sys::trap-wnaerr is called; I suppose wna stands for wrong number of arguments.


Java 8 : Lambda Function and Generic Wildcards

I have the following class class Book implement Borrowable { @Override public String toString(Function<? extends Borrowable , String> format) { return format.apply(this); } } This gives me an error that i cannot use "apply" on this(Book object). My current formatter is Function<Book, String> REGULAR_FORMAT = book -> "name='" +

Xcode 6.3.2 unexpectedly crashing on App Store submission

I was about to submit my app for TestFlight testers , the Xcode has crashed for 6th consecutive time and it is still crashing , I'm just hanged in the middle . Any suggestions what to do ? Thank you in advance for the help. Process: Xcode [1917] Path: /Applications/

C++ lambda, not seeing function and argument?

I have some code using a wrapper class around std::thread, which is using a timer struct (based upon boost::asio), to call methodToCallEachIteration() every 5000 milliseconds: class OurThreadWrapperClass{ OurThreadWrapperClass(boost::asio::io_service& = generic_timer_queue_s()); }; class A { A() : thread1(_TimerIOService){ thread1.setInterval(5000); // This sets the callback function, to be called every INTERVAL ms....

Use “Contains” to match part of string in lambda expression

I have this MVC page where I have three different "input" elements, all the same class, using the jQuery autocomplete. On any one of them I am doing this in the controller: [HttpGet] public ActionResult GetAllItemsEdit(string data, string source) { List<TextValuePair> items = InventoryControlRepository.GetAllItemsTVP(); var result1 = items.Where(item => item.Text.Contains(data.ToUpper())).ToList();...

How to call a lambda using LINQ expression trees in C# / .NET

I want to use expression trees to dynamically create a method to call a lambda. The following code runs fine for the first call to the ComposeLambda function, but the second call fails with the following error message. Incorrect number of arguments supplied for call to method 'Int32 lambda_method(System.Runtime.CompilerServices.Closure, Int32)'...

How do I mock multiple levels of DbSet.Include lambdas?

I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

Dynamic lambda wrapped with try catch

I want to filter an IEnumerable<ModuleItem> by an Where calls defined by the user (so the expression is given by a String object) So far I am able to create my filters with DynamicLinq with this code Expression<Func<ModuleItem, bool>> expr = System.Linq.Dynamic.DynamicExpression.ParseLambda<ModuleItem, bool>(value, null); The problem is that the overall...

converting List type with Lambda Java

If I have an expression: / List<Long> / / List<String> / s.getPhones().addAll(Arrays.asList(rs.getString("phones").split(","))); Can I use Java Lambda to convert types with Long.parseLong in pritty form without "for loop" ? Or even if will use for loop, it will became more "codeless". How it must look like?...

Transforming a two-variable std::function to a single-variable one

I have a function which gets two values, x and y, and returns the result: std::function< double( double, double ) > mult = []( double x, double y){ return x*y; }; Now I want to get a single-variable function for a constant y. I have written the following code, but...

linq max inside a “where” clause with an “and” condition too in lambda

I need to get a field with those conditions, my actual code in SQL is this: SELECT archivo, fechadiario FROM ri_diariodefotos WHERE [email protected] AND fechadiario = (SELECT MAX(fechadiario) FROM ri_diariodefotos WHERE [email protected]) I actually have this : RI_DiariodeFotos.Where(a=> a.Idproyecto == PROJECTID && a.Fechadiario == RI_DiariodeFotos .Where(x=> x.Idproyecto == PROJECTID) .OrderByDescending(x=>...

Share variable between two lambdas

I want to be able to share a variable in the containing scope between two lambda functions. I have the following: void holdAdd(const Rect& rectangle, Hold anonymousHeld, Hold anonymousFinish) { std::map<int,bool> identifierCollection; HoldFinish holdFinish = [=](const int& identifier) mutable { if (identifierCollection.count(identifier) == 0) return; identifierCollection.erase(identifier); anonymousFinish(); }; holdCollisionCollection.push_back([=](const int&...

Is there a way to see the body of a lambda in Racket?

Say I have this code: #lang racket (define a ((λ (x) x) ((λ (y) y) (λ (z) ((λ (w) w) z))))) I know intuitively that this lambda expression is (extensionally) equal to (λ (z) z) My question is if there is a way to print out the body of a...

How best to prevent unused variable warnings in custom assert without sizeof?

Based on advice in I've been working with my own version of assert (called emp_assert) for a while now. As such, when NDEBUG is set, my assert looks like: #define emp_assert(EXPR) ((void) sizeof(EXPR) ) This definition assures that any variables in EXPR still count as "used" in the compiler,...

How to apply a function to the elements of a pandas dataframe

I want to apply a lambda function to the elements of a dataframe, in the same way as np.sqrt returns a dataframe with the sqrt of each element. However pd.DataFrame.apply apply the function to an row or an column. Is there a similar comand that apply a lambda function on...

C# lambda expressions without variable / parameter declaration?

What's it called when a method that takes a lambda expression as the parameter, such as Enumerable.Where, is invoked without actually declaring a variable or method parameter in the expression? For example, I'm familiar with this lambda expression syntax: public string GetDigits(string input) { return new String(input.Where(i => Char.IsDigit(i)).ToArray()); }...

Java 8 map to only value type collection

I want to convert my Map <K,V> into only a Set <V>. I could not find any example anywhere, including Oracle's documentation here: All I could go further is: myMap.entrySet().parallelStream(). filter((entry) -> entry.getKey().startsWith("a")) .collect(Collectors.toSet()); This returns a Set of Map.Entry. In this example it's Map<String, String> so I would...

Nested maps in Python 3

I want to transform my list list = [" a , 1 ", " b , 2 "] into a nested list [["a","1"],["b","2"]]. The following works: f1_a = map(lambda x :[t.strip() for t in x.split(',',1)],list) but this does not work with Python 3 (it does work with Python 2.7!): f1_b...

Dividing an Expression in C# using Expression.AndAlso() causes an Exception

On my project written in C#, I've found a HUGE predicate that is used in this method of linq : public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate); this predicate works perfectly, but it as so much condition that I struggled a lot before understanding it. I would like...

State in a java.util.function.Function

Suppose that I have a class which implements java.util.function.Function. The Function needs to know about a start date and end date but these will be constant throughout the lifetime of the function. I'm considering implementing the Function with private final fields for the start and end dates, as the apply...

Why this anonymous method does not work while the lambda does?

I am learning anonymous methods, lambdas etc. and cannot find the reason why it does not work here: // this does not work MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; }); // this works MyDictionary.Keys.Where(w => w.Length == 5); ...

How can I simulate a nested function without lambda expressions in C++11?

I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot));; return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Java 8: Filtering Map to List by person's status

I'm trying to filter a Map<Long, Person> people and return only the IDs of these people having a status of SUBSCRIBED in a List<Long>. Here is the code in the old-fashioned way: public List<Long> getSubscribedPeople() { final List<Long> subscribedPeople = new ArrayList<>(); for (final Map.Entry<Long, Person> entry : subscribedPeople.entrySet()) {...

List elements disappeared when I used a lambda expression or assignment

I'm just trying to figure out what is happening in this python code. I was trying to use this answer here, and so I was tinkering with the console and my list elements just vanished. What I was doing was loading the lines into a file into a list, then...

How do I change the context of lambda?

If you run the code below you get an error. class C def self.filter_clause param_1 puts param_1 yield # context of this param is class B end def hi "hello" end end class B def self.filter(value, lambda) code = lambda { filter_clause(value, &lambda) } C.instance_exec(&code) end filter(:name, ->{ hi })...

MFC application Crashes in NTDLL.dll

I have an MFC based application. It keeps looking for a file after few seconds (using CreateTimerQueueTimer based timer) and perform some action. This is always crashing (for unknown reason) on XP. This application works fine on windows 7 and windows 8. But problem on XP is persistent. Below is...

Instance of Show for Lambda

So, I have already defined the lambda data type as such: data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq, Show) Now I want to implement an instance of Show myself. I have already the function...

Code executed after an error has occured

I have compiled and run the following C++ code with g++ version 4.8.2: vector<int> ivec{0,1,2}; int& iref = ivec[1]; for (int i=3;i<100;++i) ivec.push_back(i); iref = 10; cerr<<"After Error"<<'\n'; return 0; The program will crash as expected at line iref = 10;, because the reference is invalidated. But the string "After...

Mapping a list to Map Java 8 stream and groupingBy

I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

Casting a list of objects to another one

I have the following classes(entities): Entity(base class, has 3 props) & Category(derives from Entity and adds some other props) The problem occurs when I read data from the DB(the fill method returns a list of Entities) and the compiler doesn't allow me to cast from Entity to Category. The problematic...

Creating an Expression that returns an object

I have this method: public R TranslateExpression<R>(Expression exp) where R : DbRequest { //... } In another class I have the following method: public void Persist(E entity) { Expression expr = Expression.Return(entity); //Does not compile, but I'm looking for something like this PersistRequest request = TranslateExpression<PersistRequest>(expr); } How can I...

construction of thread using lambda expression

Can somebody explain where a thread is created on the lambda function below? What is the technique used? Can somebody recommend a reference to understand the semantics? I posted the full code now: class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) ->std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool();...

Apply a list of Functions to a Java stream's .map() method

I map a stream of NameValuePairs with a lookupFunction (which returns a Function), like this: List<NameValuePair> paramPairs = getParamPairs(); List<NameValuePair> newParamPairs = .map((NameValuePair nvp) -> lookupFunction(nvp.getName()).apply(nvp)) .flatMap(Collection::stream) .collect(toList()); But what if lookupFunction returned a Collection<Function> instead, and I wanted to perform a .map() with each of the returned Functions....

operators in predicate as argument in lambda expression

I need to use Predicate as argument in lambda expression. I tried an example code but seeing compiler error. I see that the compiler is treating the same Predicate differently for different arguments. So Predicate arguments n -> true and n -> false works but n -> n%4 == 0...

Is there a better way to do this than writing a wrapper allocator that stores a reference to a stateful allocator object?

For example: struct Foo { MyPoolAlloc<char> pool; std::vector<int , MyPoolAlloc<char>> vec_int; // The wrapper allocator would replace MyPoolAlloc<> here. std::vector<std::function<void()> , MyPoolAlloc<char>> vec_funcs; // The wrapper allocator would replace MyPoolAlloc<> here. Foo() : vec_int(pool) , vec_funcs(pool) {} // I want to store lambdas with captured variables using the custom allocator...

Image freeze when a continuation is called

I'm trying to test the continuation facility in Pharo, with this code(in the playground): | cont f | f:=[ |i| i:=0. Continuation currentDo: [ :cc | cont:=cc ]. i:=i+1. ]. f value. "1" cont. "a Continuation" However, as soon as I call the continuation saved in cont(replacing cont. by cont...

How to use lambda expression to call the comparator?

I am doing the leetcode's largest Number problem. Here is the problem: Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. and there is a 5 lines C# code:...

How to delete a row from database using lambda linq?

I want to perform a delete operation to unfriend a user in a certain android application I'm developing. The following method returns "Done" but the data doesn't delete from the table. What is the problem here? public string deleteFriend(int user, int friend) { int i = db.Friends.Where(x => x.Person.Id ==...

iOS app crash on launch using XCode debugger, runs fine without debugger

When running the app on a device (iphone), it crashes at startup without any error messages. But if the device is not connected to xcode (not in debug mode), just open up the app, it runs fine. Same code runs perfect on simulator. Never seen this before, I guess something...

java 8 fuction invocation

I have been using Java 8 from last couple of months and trying to get my head around lambdas. I have a quite bit understanding about concert. But struggling with custom functional interface execution as lambda call. If I create java Bifuctional interface implementation BiFunction<t1,t2,R> trade = (t1, t2) ->...

Stack with push and pop functions not working

This is the program. #include<iostream> #include<string> using namespace std; struct stack { int inf; stack* link; } *start, *p; void push(stack*, stack*, int); void pop(stack*, stack*); int main() { int s = 0; string thing; cin >> thing; while (thing != "end") { if (thing == "push") { push(start, p,...

How to compose two lambdas of type “delegate” in c#

Lets assume we have defined two Lambdas. Func<TInput, TOutput> a = …; Func<TInput1, TInput2, TOutput> b = …; Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates. delegate da = a; delegate db = b; In...

Java 8 lambdas nested Map

I am trying to use Java-8 lambdas to solve the following problem: Given a List<Transaction>, for each Category.minorCategory I require the sum of Transaction.amount per Category.minorCategory and a Map of Transaction.accountNumber with the sum of Transaction.amount per Transaction.accountNumber. I have this working, as per the code below. I now have...

“CLR detected an Invalid Program” when compiling a constructor for List

I'm running into a strange problem when compiling a lambda expression for a parameterless constructor into a delegate. It works for almost all types that I have tried. Only the List<> is producing a “CLR detected an Invalid Program”. A Collection<> or an inherited class from List<> would not present...

Application Crashes when an Activity that Extends ListView is 'Launched'

Here is my package thesleeplesselite.drgreenthumb; import; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class InfoBookActivity extends ListActivity { // -- AUTO-GENERATED CODE -- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_infobook); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action...

How can I suppress anonymous new runnable() can be replaced with lambda

I got "anonymous new runnable() can be replaced with lambda" warning with the following code. final ScrollView sv = (ScrollView) findViewById(; Runnable() { @Override public void run() { sv.fullScroll(ScrollView.FOCUS_DOWN); } }); I searched on Google very hard and seems to be re-write using lambda expression... final ScrollView sv =...

Select the first object that match condition or an inner object

I have a class that contains an inner list of the same class, For example: class Foo { string SearchId; List<Foo> GroupedPackages } I want to return the first "foo" instance that fits a condition, it can be in the main instance or in the inner List. This is what...

TypeScript: Lambdas and using 'this'

JavaScript frameworks often call callbacks using apply(). TypeScript's arrow notation, however, doesn't seem to allow me to access the 'this' pointer. How's it done? If it isn't, is there a place to down-vote the current 'this' handling on Lambdas?...

Check for Null in an Expression

I have an Expression that looks like this: obj => obj.Child.Name where Name is a string. What I want to do is get the value of Name. I can get it just fine by compiling the method and invoking it, however a NullReferenceException is thrown if Child is null. Is...

Android - Compiles And Runs But Crashes

So I'm trying to write code which will spawn a red circle at a random spot on the screen every 5 seconds. I wrote the code which will just spawn a red circle without repeating it every 5 seconds and it works fine. Then, when I added code (commented out)...

Expression Lambda with types known at runtime

I am trying to make some Expressions where I will be using a lambda to create two methods: a selector and condition. Simplified the usage is condition(selector(data)), but the intemediate type is only known at runtime. I have the following code which works as long as the intemediate type is...