objective-c-blocks,y-combinator , When I use Y-Combinator and block in C, I meet a strange thing in parameter value


When I use Y-Combinator and block in C, I meet a strange thing in parameter value

Question:

Tag: objective-c-blocks,y-combinator

When I try to caculate sinh−1(x) using functions:

double asinh_recursion(double  buf, double increment, double input_var, unsigned long item_count) {
    if (fabs(increment) < 1E-5) {
        return buf;
    }
    return asinh_recursion(buf + increment, increment * (-1) * (2 * item_count - 1) * (2 * item_count -1) / (2 * item_count + 1) / 2 / item_count * input_var, input_var, item_count + 1);
}
double asinh(double x) {
    if (!(fabs(x) < 1.0)) {
        printf("error asinh():wrong param x(fabs(x) > 1.0)");
        return -1.0;
    }
    return asinh_recursion(0.0, x, x * x, 1);
}

it seem works. but when I try to use block and Y-Combinator to do it:

typedef void * (^YCBlock)(void *);
YCBlock Y;
double asinh_with_block(double x) {
    if (!(fabs(x) < 1.0)) {
        printf("error asinh():wrong param x(fabs(x) > 1.0)");
        return -1.0;
    }


    Y= (YCBlock) ^ (YCBlock f) {
        return (YCBlock) ^ (YCBlock g) {
        return g(g);
        }(
        (YCBlock) ^ (YCBlock h) {
            return f(^ (void * x) { return ((YCBlock)h(h))(x); });
        }
        );
    };

    typedef double (^ RECUR_BLK_TYPE)(double, double, unsigned long);
    RECUR_BLK_TYPE recur_block = Y(^(RECUR_BLK_TYPE recur_block){
        return Block_copy(^ double (double buf, double increment, unsigned long item_count){
            if (item_count < 4) {
                printf("param:%lf,%lf,%lu\n", buf, increment, item_count);
            }

            if (fabs(increment) < 1E-5) {
                return buf;
            }
            buf = buf + increment;
            increment = increment * (-1) * (2 * item_count - 1) * (2 * item_count -1) / (2 * item_count + 1) / 2 / item_count * (x * x);
            ++item_count;
            if (item_count < 4) {
                printf("\tbuf:%lf\n", buf);
            }
            return recur_block(buf, increment, item_count);
            });
          });
    double ret = recur_block(0, x, 1);
    Block_release(recur_block);
    Block_release(Y);
    return ret;
}

but it works strangely in the output(x=0.5):

param:0.000000,0.500000,1
    buf:0.500000
param:0.500000,-0.020833,2
    buf:0.479167
param:0.500000,0.002344,3
...
asinh_with_block(0.500000):0.500000

it seem like that in the block, at some time,when I pass buf=0.479167, next time when I print it, it is still 0.500000. I wanna to find why it works like this, maybe I wrote some wrong code at somewhere...


Answer:

The problem is that your Y combinator is only made to work with an underlying function that takes one void * parameter and returns a void *. You can see that in the line:

return f(^ (void * x) { return ((YCBlock)h(h))(x); });

The block in there that takes x (one argument) and passed the x to another thing as one argument. For it to work with a recursive function of multiple arguments, this function must take those multiple arguments and pass them all on (of course, the types all need to be right too, because different types have different sizes, and the ABI for passing and returning things of different types is different). So you will need a different Y combinator for each function signature.

You have a recursive function that takes three parameters (two doubles and an unsigned long) and returns a double. You can (minimally) make it work by changing the relevant block in the Y combinator and coercing it from the wrong type to the right type:

return f(^ (double buf, double increment, unsigned long item_count) {
    return ((RECUR_BLK_TYPE)((YCBlock)h(h)))(buf, increment, item_count);
});

But to really make it clean with correct type safety without this unsafe casting would require you to carefully set up the types. Something like this:

typedef double (^Func)(double, double, unsigned long);
typedef Func (^FuncFunc)(Func);
typedef Func (^RecursiveFunc)(void *);
typedef Func (^YCBlock)(FuncFunc);

Y = ^(FuncFunc f) {
    return ^(RecursiveFunc g) {
        return g(g);
    }(
        ^(void *temp) {
            RecursiveFunc h = temp; // trick to hide the recursive typing
            return f(^(double buf, double increment, unsigned long item_count) {
                return h(h)(buf, increment, item_count);
            });
        }
    );
};

Related:


Retain loop in a block


ios,objective-c,sprite-kit,objective-c-blocks,retain-cycle
I'm trying to get variables and properties in self in a block for actions to complete, but, if I reference self or a global variable in self when self is the object running the block, it warns me of a retain loop. Here's what I'm doing: I'm adding actions to...

Can Swift return value from an async Void-returning block?


swift,return,closures,firebase,objective-c-blocks
I want to create a function to check if user_id is already in my database. class func checkIfUserExsits(uid:String) -> Bool { userRef.childByAppendingPath(uid).observeSingleEventOfType(.Value, withBlock: { (snapShot: FDataSnapshot!) -> Void in if snapShot.value is NSNull { return false } else { return true } }) } However, observeSingleEventOfType is a API provided...

Block completion handler reference is nil after completing background fetch


ios,objective-c,objective-c-blocks,background-process
I am trying to implement a background fetch of an RSS Feed using performFetchWithCompletionHandler, but when I want to call the completion handler it's nil. Am I missing a way to retain my reference to self.completionHandler? Am I declaring self.completionHandler correctly? in app delegate: //background fetch new RSS Feeds -(void)application:(UIApplication...

Background performFetchWithCompletionHandler using Blocks causes crash


ios,objective-c,objective-c-blocks,background-process
I have an app that successfully fetches and displays RSS Feeds that I'd like to add background fetch. I receive: Thread 1 EXC_BAD_ACCESS (code=1, Address=0x10) where indicated below. In app delegate: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //setup background fetch [application setMinimumBackgroundFetchInterval: UIApplicationBackgroundFetchIntervalMinimum]; return YES; } //background fetch new RSS...

Objective-C - block loop from continuing until delegate method is called


objective-c,json,objective-c-blocks,grand-central-dispatch,nsurlconnectiondelegate
In each loop, I initialize a connector class with an id that is used to perform a JSON call. The problem is, is that this loop continues to iterate before the connectionDidFinishLoading delegate method of the connector class completes, parses the JSON as needed then uses a delegate method with...

Objective-C can you use fast enumeration in place of “for (i = 0; i < X; i++)”


objective-c,objective-c-blocks,fast-enumeration
Let's say I've got a basic integer iteration like so: NSInteger rowCount = self.rowCount; for (int i = 0; i < rowCount; i++) { // stuff! } Is there a way to implement this using fast enumeration blocks? I could certainly create an array of integers 0 - self.RowCount, but...

Clarifications needed for a crash using NSArray, blocks and Manual Reference Counting


objective-c,memory-management,objective-c-blocks
I need some clarifications on a crash I'm encountering using NSArray, blocks and Manual Reference Counting. My goal is to store blocks on a collection (NSArray in this case) in order to reuse them in the future. I've setup a small sample to replicate the issue. In particular, I have...

typedef in cocoa blocks


objective-c,cocoa,objective-c-blocks
I have a simple Blocks and typedef doubt. Consider the following codes, I've some typedef and two methods, second one is commented out. My doubt is regarding the first one. Should I use this one? Any issues or something that may arise in future? typedef void (^MySuccessBlock)(MyServiceResponse *response); typedef void...

How do I declare a block that returns a UIView?


ios,objective-c,objective-c-blocks
I keep trying to create a block that will return a UIView after it fetches it from the background. I got the fetch from the background part, but I am having trouble setting up the block. This code works, but I want a block that can be called from another...

Blocks in Swift shows error “Missing argument for parameter #2 in call” [closed]


objective-c,swift,objective-c-blocks
I'm now using Jonas Gessner's JGActionSheet with Swift in my project, and the sample was written by Objective-C, when I tried to convert the block to Swift, Xcode shows the error "Missing argument for parameter #2 in call", here is the code I written and the screenshot: Objective-C Sample JGActionSheet...

Confusion over how I should use weakSelf in blocks


ios,objective-c,parse.com,objective-c-blocks
I have a lot of blocks in my code. I have a process for initialising a user upon login, I am using Parse.com as my backend: PFQuery *messageBankQuery = [PFQuery queryWithClassName:@"messageBank"]; [messageBankQuery whereKey:@"username" equalTo:[PFUser currentUser].username]; [messageBankQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) { if(!error){ [self setupUserWithMessageBank:object]; }//end no error if else{ NSLog:(@"error");...

MKDirections calculateETAWithCompletionHandler: in background state


ios,objective-c,mapkit,objective-c-blocks
I have an app which monitors significant location changes. Upon receiving a new calculation I want to calculate the duration from the current location to a specified location. To calculate the duration I use calculateETAWithCompletionHandler: from the MKDirections class. Everything works as expected as long as the app is in...

Block leak with __block variable


ios,objective-c,memory-leaks,objective-c-blocks,weak-references
I have a big memory leak that I have pinpointed to happen in/on requestContentEditingInputWithOptions: method. If I understand it right it happens with the img variable. If I make it __block __weak the image is nil already after I assign it (img = [UIImage...]). Am I being silly somewhere? Or...

Is it possible to call a block completion handler from another function in iOS?


ios,swift,block,objective-c-blocks
I have a custom UIView with a UITapGestureRecognizer attached to it. The gesture recognizer calls a method called hide() to remove the view from the superview as such: func hide(sender:UITapGestureRecognizer){ if let customView = sender.view as? UICustomView{ customView.removeFromSuperview() } } The UICustomView also has a show() method that adds it...

How to make a boolean both static and __block? in iOS?


objective-c,objective-c-blocks,static-variables
bool _hintExist; - (void)showNotReachable { if (_hintExist) { return; } NSLog(@"Show a hint"); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ _hintExist = NO; }); } The code above is fine. There is a button to trigger the method. Actually, I don't need _hintExist be a global variable. I want to make...

Is it correct to use local variable name “self” in blocks?


ios,objective-c-blocks,self
I`ve found that construction __strong typeof(self)self = weakSelf. It allows remove NSAssert macro self catching, but I am in doubt is it right to use it in that way? __weak typeof(self)weakSelf = self; self.signupBlock = ^{ __strong typeof(self)self = weakSelf; NSLog (@"%d", self.property) NSAssert((self.property > 5), @"Some message"); } Pls...

How can I wait for delegate to complete before returning completion handler in method?


ios,xcode,delegates,objective-c-blocks,quickblox
I have a method which performs an action. - (void)mutualDeleteDialog:(QBChatDialog *)dialog success:(void (^) ())successBlock failure:(void (^)(NSError *))failureBlock { QBChatMessage *deleteMessage = [self generateDeleteDialogMessage:dialog]; [self sendMessage:deleteMessage success:^{ [QBChat deleteDialogWithID:dialog.ID delegate:self]; } failure:^(NSError *error) { failureBlock(error); }]; The deleteDialogWithID method calls a third party service and calls a delegate method when complete....

Why is this NSString null in a FireBase query block?


ios,objective-c,firebase,objective-c-blocks,nsmutabledictionary
I can't figure out why this string is null inside the FQuery block. My app keeps crashing when I build the dailyLog MutableDictionary at the user key; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM dd, YYYY"]; NSString *userID = [[self.userProfile objectForKey:@"userID"] copy]; self.logFirebase = [[Firebase alloc] initWithUrl:@"https://urlName.firebaseio.com/DailyLog"]; [[[self.logFirebase queryOrderedByPriority]...

iOS: UIBackgroundFetchResult completion handler inside of block


ios,objective-c,objective-c-blocks
Could use a little help here, as my understanding of blocks and completion handlers is very limited. I'm trying to implement background fetching in iOS while following along with this tutorial and changing things out as necessary: http://www.appcoda.com/ios7-background-fetch-programming/ I've implemented the necessary precursors to get background fetch enabled and have...

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?...

iOS(Objective-C). Application crash when getting block from array


ios,objective-c,memory-management,objective-c-blocks
Have a question about blocks in objective-c. For example I have a list of actions. I'm initializing an array of blocks: self.actions = @[ ^() { [self showObject:self.object_1]; }, ^() { [self showObject:self.object_2]; }, ^() { [self showObject:self.object_3]; } ]; And calling them when some row is pressed: - (void)pressedRowAtIndex:(NSInteger)index...

RACSignal combineLatest: cannot reduce


objective-c,objective-c-blocks,reactive-cocoa
I have a horrible compile problem while trying to reduce a couple of signals. RACSignal* contactIdentifierSignal = RACObserve(self, contactIdentifier); RACSignal* displayNameSignal = RACObserve(self, displayName); RACSignal* mappedThing = [RACSignal combineLatest:@[contactIdentifierSignal, displayNameSignal] reduce:^id(NSString* identifierValue, NSString* displayNameValue){ return @([identifierValue length] > 0 && [displayNameValue length] > 0); }]; The error that I get...

Translating Objective-C function call to Swift


ios,objective-c,swift,objective-c-blocks,swift-closures
This is what I have so far... func rightButtonItemsInRevealTableViewCell(revealTableViewCell: SWRevealTableViewCell!, handler:((Bool) -> (NSArray))!) { var item1: SWCellButtonItem = itemWithTitle("Delete", { (var success) in println("\(success)") } }); item1.backgroundColor = UIColor.redColor(); item1.tintColor = UIColor.whiteColor(); item1.width = 75; return item1; } I found this that is somewhat helpful but I am still getting...

Pass by reference for blocks


objective-c-blocks
Is there a way to pass blocks by reference? Below code prints out "Block is nil" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { void (^block)(void) = nil; [self assignBlock:block]; if ( block ) {block();} else{NSLog(@"Block is nil");} return YES; } - (void)assignBlock:(void (^)(void))blockToAssign { blockToAssign = ^(void){ NSLog(@"Block assigned"); }; }...

Method that returns block


ios,objective-c,cocoa-touch,objective-c-blocks
I wrote a method that can be used with a dot notation, using block tricks - (RaginiDBQuery *(^)(id object))where; This method can be called using a dot notation since basically it doesn't receive any parameters, (it does, but by using the block returned) So I can call it like so:...

Incompatible block pointer type? Cannot return NSArray


objective-c,nsarray,objective-c-blocks
I have a block we return an array in callback. Then I create another method to store that array as below: - (NSArray *)getUserData{ [self fetchDataByUserId:self.userID completionHandler:^(NSArray *record) { return record; }]; } I received this kind of error so please help me, I don't understand. "Incompatible block pointer types...

When I use Y-Combinator and block in C, I meet a strange thing in parameter value


objective-c-blocks,y-combinator
When I try to caculate sinh−1(x) using functions: double asinh_recursion(double buf, double increment, double input_var, unsigned long item_count) { if (fabs(increment) < 1E-5) { return buf; } return asinh_recursion(buf + increment, increment * (-1) * (2 * item_count - 1) * (2 * item_count -1) / (2 * item_count +...

Error return a NSString inside a block


objective-c,objective-c-blocks
I'm trying to declare a method and return two values BOOL, NSString for that I'm doing: typedef void(^myCompletion2)(BOOL, *NSString); The problem with this code is that this command return the warning message: type specifier missing, defaults to 'int' How to solve this problem?...

blocks within blocks and variable capture


objective-c,objective-c-blocks
When I have a method performing the work from a callback and the method itself references the class's properties, is that considered a leak with the way blocks are captured? @interface ClassA - (void)performClassAWorkItem1:(void (^)(NSArray *list, NSError *err)block; - (void)performClassAWorkItem2:(void (^)(NSString *string, NSError *err)block; @end @interface ClassB @property (nonatomic, strong)...

Passing the object back in a block


objective-c,objective-c-blocks
There's a number of questions and answers about how to avoid retain cycles when accessing self inside a block such as this... MYObject *obj = [[MYObject alloc] init]; __weak typeof(obj) weakObj = obj; obj.completionBlock = ^(){ NSLog(@"my message %@", weakObj.message); }; But with classes like NSTask the termination handler actually...

Retain Cycles for Blocks Inside of Blocks


ios,objective-c,objective-c-blocks
Do I have to continuously declare weak references to break retain cycles for blocks inside of blocks? __weak typeof(self) weakSelf = self; [self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) { typeof(self) strongSelf = weakSelf; [strongSelf doSomething]; [strongSelf setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) { //do I need to create another...

Objective-c: How to make multiple async service calls and block until they are all complete


objective-c,asynchronous,objective-c-blocks
I have a senario that requires me to make multiple call to a web api. The following is an example. getDataAsync:(NSDictionary *)dictionary withCompletion: (void (^)(NSDictionary*))completion { __block int counter = n; // the number of async blocks __block NSMutableDictionary *output = [[NSMutableDictionary alloc] init]; void (^returnBlock)(void) = ^{ counter--; if(counter...

invoking block in array with parameters


ios,arrays,objective-c-blocks
I've seen the answer about invoking a block that is stored in an array, but I can't get it to work with parameters. I store the array an a part of an object, then when it's in a method, I want to invoke it, however, I need parameters. Also, is...

Objective c block in a block


ios,objective-c,iphone,objective-c-blocks
Lot of blocks here! I am trying to use blocks to perform an operation on each record present in a dictionary. I created a weak reference of the strongRecordBlock and used that to call itself in the strongRecordBlock. It all worked fine until I introduced my actual operation (DataManager addRecord)...

Do methods called from within a block need to use weakSelf?


objective-c,objective-c-blocks,retain-cycle
If the code inside a block calls a method, will a retain cycle exist if that method references self? In other words, does all code downstream of a block need to use the weakSelf/strongSelf pattern? For example: __weak __typeof__(self) weakSelf = self; Myblock block = ^{ [weakSelf doSomething]; }; ....

Undefined selector with Objective-C runtime - blocks


ios,objective-c,iphone,objective-c-blocks,objective-c-runtime
I'm trying to create a function where multiple times I do the same thing. I've deceided to go with a block this time. However after writing following code: - (BOOL)readyForProcessing { void (^notDeclaredError)(id) = ^(id missingObject) { NSString *missingObjectName = NSStringFromSelector(@selector(missingObject)); NSString *errorDescription = [NSString stringWithFormat:@"You need to provide %@...

Confusion regarding blocks in ios


ios,objective-c-blocks
I have a bit of confusion regarding blocks. Say for example I have a block with completion BOOL: -(void) addNewSubGoalToLocalDatabaseAndParse:(CompletionBlock )cb { SubGoal* subGoalToAdd = [SubGoal new]; subGoalToAdd.name = subGoalName; subGoalToAdd.parentGoal = goal; Score* scoreToAdd = [Score new]; scoreToAdd.score = 0; scoreToAdd.subgoal = subGoalToAdd; [subGoalToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {...

Scribble uncovering bug in block use I don't understand


xcode,osx,debugging,memory,objective-c-blocks
I have a bug which I have uncovered by enabling Scribble in Xcode, fixing the bug is not an issue, it isn't implemented in the best way, I can just remove the whole block, but I don't understand why I am getting the issue in the first place, which tells...

BAD ACCESS after block within a block is called (iOS)


ios,firebase,objective-c-blocks,exc-bad-access
I have a block where I am checking a user's status property from firebase. If the status property is 'free' I want to return from the block, otherwise I want to search for another user and check their status and do so until a 'free' user has been found: void(...

Unrecognized selector sent to instance when assigning a block property


ios,objective-c,objective-c-blocks
I have an app that may require the user to authenticate during navigation. If this is the case, I'd like the login event to return a callback back to the operation that requested the login event, for it to know that the login was either successful or not. For example,...

How to call instance methods inside a block?


ios,objective-c-blocks
I want to call instance methods inside a block. Here is the method that I am working with, [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{ [self myInstanceMethod]; }]; But I am not able to reference self from inside this block. What should I do? EDIT: I am sorry that I posted this question...

blocks and the stack


cocoa,objective-c-blocks
According to bbum: 2) Blocks are created on the stack. Careful. Consider: typedef int(^Blocky)(void); Blocky b[3]; for (int i=0; i<3; i++) b[i] = ^{ return i;}; for (int i=0; i<3; i++) printf("b %d\n", b[i]()); You might reasonably expect the above to output: 0 1 2 But, instead, you get: 2...

objective-c using blocks with recursion


ios,objective-c-blocks
I am coding an iphone app. And when I used blocks with recursion in Objective-C, I got a warning message of Capturing addImageToUploadEntity strongly in this block is likely to lead to a retain cycle. I created a block called addImageToUploadEntity is used to call an async function [self.submissionEntity addImageData:...

Adding a variable to a block


ios,objective-c,objective-c-blocks
I'm using a UIAlertView + block Category found here. I'm having trouble following how he has created the blocks: typedef void (^DismissBlock)(int buttonIndex); I understand this, use it on creating my own blocks. So I created mine: typedef void (^DismissBlockWithView)(UIAlertView *alertview, int buttonIndex); I think I understand what is happening...

Is a __block variable assignment thread-safe to read immediately after the block?


ios,objective-c,synchronization,thread-safety,objective-c-blocks
__block NSHTTPURLResponse *httpResponse; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) httpResponse = (NSHTTPURLResponse *)response; } dispatch_semaphore_signal(semaphore); }]; [task resume]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); Is it safe to read httpResponse after this? The semaphore waits for the block to compete execution. If...

Objective-C: Animations in Blocks


ios,objective-c,animation,objective-c-blocks
I have a UIImageView sliderPump which I move from right to left side of the screen infinite times by calling two methods one after another: -(void)pumpGoesRight { if (slide) { [UIView animateWithDuration:0.8 animations:^ { [sliderPump setFrame:CGRectMake(sliderPump.frame.origin.x+235, sliderPump.frame.origin.y, sliderPump.frame.size.width, sliderPump.frame.size.height)]; } completion:^(BOOL finished) { [self pumpGoesLeft]; }]; } else return; }...

Is it ok to override completionBlock property of NSOperation with different parameter types?


objective-c,cocoa,objective-c-blocks,nsoperation
Marcus Zarra's "Core Data" (2nd edition) book lists an example where in an NSOperation subclass he overrides the completionBlock property: @property (copy) void (^completionBlock)(void) NS_AVAILABLE(10_6, 4_0); with typedef void (^ExportCompletionBlock)(NSData *jsonData, NSError *error); @property (nonatomic, copy) ExportCompletionBlock completionBlock; which in Xcode 6 under 10.10 results in the following warnings: ‘atomic’...

I'm having trouble with my attempt of objective-c block equivalent in swift


objective-c,swift,objective-c-blocks,swift-closures
Here is the objective-c code: options.onPan = ^(MDCPanState *state){ if (state.thresholdRatio == 1.f && state.direction == MDCSwipeDirectionLeft) { NSLog(@"Let go now to delete the photo!"); } }; Swift: var options = MDCSwipeToChooseViewOptions() options.delegate = self options.likedText = "Keep" options.likedColor = UIColor.blueColor() options.nopeText = "Delete" options.onPan = { (state: MDCPanState) in...

Replacing Delegates with Blocks


ios,objective-c,objective-c-blocks
I have recently started learning Objective C and came across Blocks/Closures. They look much like Annonymous inner classes in Java to me. I have read somewhere that Blocks can be used to replace Delegates. This confuses me as in case of Delegates you signal a method when a specific task...