Skip to content

Update fifelse documentation to reflect evaluation behavior - #6151

Merged
tdhock merged 11 commits into
masterfrom
fifdoc
Jun 3, 2024
Merged

tdhock merged 11 commits into
masterfrom
fifdoc

Conversation

@joshhwuu

@joshhwuu joshhwuu commented May 27, 2024 •

Copy link
Copy Markdown
Member

Closes #4549

fifelse evaluates both yes and no arguments, regardless of the value of test. This makes it unfit for recursive functions as the evaluation will cause an infinite loop of calls.

Changed documentation to better reflect this behavior, along with a simple example to showcase the difference against base ifelse:

ifelse(1 == 1, print("yes"), print("no"))
# [1] "yes"
fifelse(1 == 1, print("yes"), print("no"))
# [1] "yes"
# [1] "no"

Also mentioned that fcase can be used instead for recursive calls. Does fcase documentation also need updating? I noticed that the when and value pair is evaluated, even if the when doesn't bind, which means:

gcd_dt <- function(x,y) {
  r <- x%%y;
  return(data.table::fcase(!r, y, r, gcd_dt(x, y)))
}

works, but

gcd_dt <- function(x,y) {
  r <- x%%y;
  return(data.table::fcase(!r, y, r, gcd_dt(x, y))) # (when value pair swapped)
}

doesn't, due to the same reason that fifelse doesn't.

Comment thread man/fifelse.Rd Resolved
@joshhwuu
joshhwuu requested a review from Anirban166 May 30, 2024 20:47
Comment thread man/fifelse.Rd Resolved
@joshhwuu

joshhwuu commented Jun 1, 2024 •

Copy link
Copy Markdown
Member Author

From R-CMD-Check:

  > # fcase can be used for recursion, unlike fifelse
  > gcd_dt <- function(x,y) {
  +   r <- x
  +   return(fcase(!r, y, r, gcd_dt(x, y))) # Recursive call must be in the last when-value pair
  + }
  > gcd_dt(10, 1)
  Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
  Execution halted

not sure why mod operator isn't showing up here, will investigate

Edit:

Rd files have to use escaped percent symbols, otherwise it marks the beginning of an Rd comment

Comment thread man/fcase.Rd Resolved
Comment thread man/fcase.Rd
)

# fcase can be used for recursion, unlike fifelse
gcd_dt = function(x,y) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i guess this is greatest common denominator? can you please add a comment to explain?

@tdhock tdhock left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good to me

@tdhock
tdhock merged commit 8d1377e into master Jun 3, 2024
@joshhwuu
joshhwuu deleted the fifdoc branch June 3, 2024 21:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fifelse did not work in recursive function

3 participants