implicit return? [🇷 for BE/BA]

posted by Helmut Homepage – Vienna, Austria, 2019-04-29 01:38 (1817 d 19:59 ago) – Posting: # 20259
Views: 6,579

Hi ElMaestro,

❝ My functions almost always look like this:

❝ Foo=function(bar)

❝ {

❝   ##blah blah, conditions and functionality and loops and loads of curly braces here.
❝   ##whatever happens in loops and conditions it sets a variable called e.g. rslt


❝   return(rslt) ##I always have a line at the end that looks like this!

❝ }


Good practice. I use it in longer functions as well and in ones which become part of a package, always. Only very, very slightly slower:
library(microbenchmark)
impl <- function(x) {
  if (x == 0) {
    "foo"
  } else {
    "bar"
  }
}
expl <- function(x) {
  if (x == 0) {
    return("foo")
  } else {
    return("bar")
  }
}
braces.with.suspenders <- function(x) {
  if (x == 0) {
    res <- "foo"
  } else {
    res <- "bar"
  }
  return(res)
}
res <- microbenchmark(impl(round(runif(1), 0)),
                      expl(round(runif(1), 0)),
                      braces.with.suspenders(round(runif(1), 0)),
                      times=3000L)
print(res)

Unit: microseconds
                                      expr   min    lq     mean median    uq    max neval cld
                  impl(round(runif(1), 0)) 1.811 1.812 1.976830  1.813 2.114  5.434  3000  a
                  expl(round(runif(1), 0)) 1.811 1.812 1.976926  1.813 2.114  6.340  3000  a
braces.with.suspenders(round(runif(1), 0)) 1.811 1.812 2.027029  2.114 2.114 16.905  3000   b

Dif-tor heh smusma 🖖🏼 Довге життя Україна! [image]
Helmut Schütz
[image]

The quality of responses received is directly proportional to the quality of the question asked. 🚮
Science Quotes

Complete thread:

UA Flag
Activity
 Admin contact
22,988 posts in 4,825 threads, 1,661 registered users;
105 visitors (0 registered, 105 guests [including 2 identified bots]).
Forum time: 21:38 CEST (Europe/Vienna)

The only way to comprehend what mathematicians mean by Infinity
is to contemplate the extent of human stupidity.    Voltaire

The Bioequivalence and Bioavailability Forum is hosted by
BEBAC Ing. Helmut Schütz
HTML5