Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid significant logic inside of for loops #19

Open
cmatKhan opened this issue Jul 17, 2023 · 2 comments
Open

Avoid significant logic inside of for loops #19

cmatKhan opened this issue Jul 17, 2023 · 2 comments

Comments

@cmatKhan
Copy link
Member

OK -- not quite accurate, since using map or apply is just a for loop under the hood.

But, the point is that for loops that have significant logic in them are difficult to debug.

What is better is to take a page from the book of functional programming and write the
logic which executes on any given iteration of the loop into a function (or a number of functions)
and then apply that function(s) over the input list.

So, plot_metrics, rather than this:

 for (i in 1:length(metric_dfs_by_net[[1]])) {
    metric_dfs[[i]] <- do.call(cbind, lapply(unname(metric_dfs_by_net), "[[", i))
  }

  # assemble y-axis labels
  to_plot <- c(sum, pe
  ... # it goes on for many lines ....

write the logic inside of that loop into a function

@cmatKhan cmatKhan changed the title Avoid for loops in functions Avoid significant logic inside of for loops Jul 17, 2023
@cmatKhan
Copy link
Member Author

cmatKhan commented Jul 17, 2023

Same here

@cmatKhan
Copy link
Member Author

I'm not sure what exactly is happening here -- there are some nested for loops and the if statement is long. will need to run the code.

But, rather than using a print statement, in general using a logger is cleaner. Gives both you and the user a lot more control over how, where and when the message is printed. I like futile.logger in R.

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

No branches or pull requests

1 participant