Skip to contents

Wrapping a function in perhaps will modify it to return the expected value or a default value in some circumstances. If the function would normally return an error or warning the modified function will return a default value, otherwise it will return the expected value. If a predicate function is provided with the parameter ensure, if the predicate returns TRUE when evaluated on the return value of the function, then the expected value will be returned by the modified function, otherwise it will return the default value.

Usage

perhaps(.f, default, ensure = function(a) TRUE, allow_warning = FALSE)

Arguments

.f

A function to modify

default

A default value

ensure

A predicate function

allow_warning

Whether warnings should result in the default value

Value

A function which returns the expected value or the default value

Examples

perhaps(mean, default = 0)(1:10)
#> [1] 5.5
perhaps(mean, default = 0, allow_warning = TRUE)("hello")
#> Warning: argument is not numeric or logical: returning NA
#> [1] NA
perhaps(sqrt, default = 0)("hello")
#> [1] 0
perhaps(sqrt, default = 0, ensure = not_infinite)(-1)
#> [1] 0