moodymudskipper / tag

Build function operator factories supporting the tag$function(args) notation
GNU General Public License v3.0
13 stars 1 forks source link

Formalism and API reboot #19

Closed moodymudskipper closed 5 years ago

moodymudskipper commented 5 years ago

1) Redefining everything

We take the existing definition and tweak them to make them more rigorous, enrich them, and then define our own terms.

In this package :


2) Examples :

converting to tag_adverb

The advantage of converting an adverb/ function operator to a tag_adverb is that it keeps it original behaviour and gains the advantage of being able to use $.tag_adverb, so fun <- as_tag_adverb(fun) shouldn't break any code. We can even use set_as_adverb on packaged function to make them compatible with $.tag_adverb.

library(purrr)
safely2 <- as_tag_adverb(safely)
safely(log, otherwise = NA_real_)(100, 10)
safely2(log, otherwise = NA_real_)(100, 10)
safely2$log(100, 10, otherwise = NA_real_)
as_tag_adverb(safely)$log(100, 10, otherwise = NA_real_)
set_as_adverb(safely)
safely(log, otherwise = NA_real_)(100, 10) # still works
safely$log(100, 10, otherwise = NA_real_)

## output for all :
#> $result
#> [1] 2
#> 
#> $error
#> NULL

class(safely2)
#> [1] "tag_adverb" "function"
f1 <- safely2(log, otherwise = NA_real_)
class(f1)
#> [1] "tagged_function" "function"
f2 <- safely2$log
class(f2)
#> [1] "tagged_function" "function"

converting to tag

safely3 <- as_tag(safely)
safely3(otherwise = NA_real_)$log(100, 10)
safely3()$log(100, 10, otherwise = NA_real_)
safely3$log(100, 10, otherwise = NA_real_)
as_tag(safely)$log(100, 10, otherwise = NA_real_)

## output for all :
#> $result
#> [1] 2
#> 
#> $error
#> NULL

class(safely3)
#> [1] "tag" "function"
g1 <- safely3(otherwise = NA_real_)
class(g1)
#> [1] "tag_adverb" "function"
g2 <- safely3(otherwise = NA_real_)$log
class(g2)
#> [1] "tagged_function" "function"
g3 <- safely3()$log
class(g3)
#> [1] "tagged_function" "function"
g4 <- safely3$log
class(g3)
#> [1] "tagged_function" "function"

We recommend using adverb or adjective names for tags and tag_adverbs. Strict guidelines appear to be hard to follow in practice with functional operators but we suggest the following :

# bracket form
using(iris)$plot(Petal.Length, Petal.Width)
grouping_by("Species")$summarize_all(mean)

# dollar form, looks less good but is less likely to be used for those :
using$plot(Petal.Length, Petal.Width, .with = iris)
grouping_by$summarize_all(mean, .by = "Species")
moodymudskipper commented 5 years ago

archived