2

Can we write Continuation passing style code in Objective C? If yes, could you please give some examples?

Kun Hu
  • 417
  • 5
  • 11

1 Answers1

1

Continuation Passing Style, or CPS, is a style of programming using anonymous functions to replace return statements. Instead of returning a value, a function will take another function as a parameter. Then, when it gets to the point where it would have returned a value, it calls the passed-in function with the value as a parameter instead.

In Objective-C, we now have anonymous functions in the form of blocks, so CPS can be achieved using blocks.

Here's an example of how CPS looks. This is the standard-style code:

NSString *string = [obj stringWhatever];
    // use string

And here it is converted to Continuation Passing Style:

[obj stringWhatever: ^(NSString *string) {
    // use string
}];
Shamsudheen TK
  • 30,739
  • 9
  • 69
  • 102
  • Thanks! Can you give an example on how to pass a block to another block? BTW, is it possible to pass multiple parameters? – Kun Hu Jan 22 '14 at 04:40
  • this will help you https://mikeash.com/pyblog/friday-qa-2010-02-05-error-returns-with-continuation-passing-style.html – Shamsudheen TK Jan 22 '14 at 04:41
  • I try to use this code, but it doesn't work..Here is my code: NSDate *obj = [NSDate date]; [obj description: ^(NSString *s) { NSLog(@"%@",s); }]; – Kun Hu Jan 22 '14 at 04:49
  • @KunHu You can't just arbitrarily take any random method and turn it into a continuation method. `stringWhatever` and `stringWhatever:` are **two different methods** with different implementation semantics. – bbum Jan 22 '14 at 05:47
  • @bbum Could you please post an answer for more details? Thanks in advance :-) – Kun Hu Jan 22 '14 at 06:21
  • 1
    @KunHu Are you familiar with CPS in other languages? It works exactly the same. If you need an introduction to Objective-C, there are plenty of books. – molbdnilo Jan 22 '14 at 16:13
  • @molbdnilo I'm new with CPS, I've only seen some code in Python. I am comfortable with Objective-C, but not familiar with the blocks. – Kun Hu Jan 22 '14 at 17:02
  • @KunHu [This](https://mikeash.com/pyblog/friday-qa-2010-02-05-error-returns-with-continuation-passing-style.html) looks like a decent crash-course in Objective-C (didn't read it thoroughly). CPS is more common in languages like ML/Haskell/Scheme, so the literature is richer there. – molbdnilo Jan 22 '14 at 17:38