View source: R/parsers_basic.R
satisfy | R Documentation |
satisfy()
turns a logical function into a parser that recognizes strings.
satisfy(b)
b |
a boolean function to determine if the string is accepted. |
Notice (see pseudocode) that satisfy
fails when presented with empty
input, so it is futile to write predicate functions that would recognize
such input.
A parser.
satisfy(b)(x): if x==null then fail()(x) else if b(x[1]) then succeed(x[1])(x[-1]) else fail()(x)
where x[1]
is the first element of x
, x[-1]
all subsequent elements
(or null
if it only has one element). null
is the empty vector,
equivalent to character(0)
in R.
# define a predicate function that tests whether the next element starts
# with an 'a'
starts_with_a <- function(x) grepl("^a",x)
# Use it in the satisfy parser
satisfy(starts_with_a)(c("abc","def")) # success
satisfy(starts_with_a)(c("bca","def")) # failure
# Using an anonymous function
satisfy(function(x) {as.numeric(x)>10})("15") # success
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.