11

In package pryr, there is a function called parent_promise.

I know what a promise is, but I'm not familiar with the term parent promise. Furthermore, I don't really understand the example in the documentation, perhaps because I don't know what I'm looking for.

library(pryr)
example(parent_promise)
# prnt_p> f <- function(x) g(x)
# prnt_p> g <- function(y) h(y)
# prnt_p> h <- function(z) parent_promise(z)
# prnt_p> h(x + 1)
# x + 1
# prnt_p> g(x + 1)
# x + 1
# prnt_p> f(x + 1)
# x + 1

To help me get a better understanding of the above example, can someone explain what a parent promise is, and if/how it differs from a regular promise?

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245

1 Answers1

13

There's no special thing called a "parent promise." There are just promises. But a promise might point to another promise. The parent_promise function basically walks up the chain of promises to find the first non-promise.

So when you call f(x), that in turn calls g(y) with y (promise)-> x. Since you never evaluate y, that parameter is passed along as a promise to h(z) with z (promise)-> y. So

z (promise)-> y (promise)-> x (promise)-> x+1

So calling parent_promise(z) goes up the chain to find the first non-promise object which in each of these cases is the expression x+1

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • So, if the parent promise points to another promise, and the parent promise is evaluated, does that mean all other promises in the chain are evaluated? – Rich Scriven Aug 27 '14 at 01:52
  • I'm not quite sure I understand what you're getting at. In order to resolve a promise, you must evaluate everything up the chain. And once it's resolved, you can't point a new promise to original promise any more so they chain can't descend. – MrFlick Aug 27 '14 at 02:05
  • Thanks, that's what I was asking. – Rich Scriven Aug 27 '14 at 02:20
  • 3
    BTW I'd now recommend looking at https://github.com/hadley/lazy for related functions and documentation and vignettes – hadley Aug 27 '14 at 19:14