https://github.com/moodymudskipper/private
private closures for closures
https://github.com/moodymudskipper/private
Last synced: 25 days ago
JSON representation
private closures for closures
- Host: GitHub
- URL: https://github.com/moodymudskipper/private
- Owner: moodymudskipper
- License: other
- Created: 2023-05-04T22:26:24.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-05-05T15:30:24.000Z (almost 2 years ago)
- Last Synced: 2024-11-26T01:46:43.270Z (5 months ago)
- Language: R
- Size: 8.79 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.Rmd
- License: LICENSE
Awesome Lists containing this project
- jimsghstars - moodymudskipper/private - private closures for closures (R)
README
---
output: github_document
---```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
```# private
* Functions that are defined in the body of other functions cannot be tested easily
and clutter the body of the parent function, it's also not always clear if they use
lexical scoping or not
* If we move these functions to the namespace they make the codebase harder to
understand because we lose this relationship{private} proposes a solution to these problems.
## Installation
Install with:
``` r
remotes::install_github("moodymudskipper/private")
```## Example
```{r example}
library(private)
print_cubed <- function(x) {
x |> cube() |> format()
}
print_cubed %private% cube <- function(x) {x * square(x)}
# this works recursively
print_cubed %private% cube %private% square <- function(x) {x^2}
print_cubed %private% format <- function(x) {paste("Cubed value:", x)}print_cubed(3)
# printing methods show the class, children and namespace
print_cubedprint_cubed %private% format
print_cubed %private% cube
print_cubed %private% cube %private% square
# private closures are not bound to the local environment (the namespace if we're in a package)
ls()ls(environment(print_cubed))
ls(environment(print_cubed %private% cube))
# we can test the private methods
(print_cubed %private% cube)(4)
```# Private S3 methods
Defining private S3 methods is straightforward
```{r, error = TRUE}
print_vec <- function(data) {
data <- as.character(data)
writeLines(sprintf("%s: %s", seq_along(data), data))
invisible(NULL)
}print_vec %private% as.character.data.frame <-
function(x, ...) {stop("can't convert a data frame to a character")}
print_vec(letters[1:3])
print_vec(cars)
```