Learn R Programming

parcr (version 0.5.1)

satisfy: Matching input using a logical function

Description

satisfy() turns a logical function into a parser that recognizes strings.

Usage

satisfy(b)

Value

A parser.

Arguments

b

a boolean function to determine if the string is accepted.

Pseudocode


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.

Details

Notice (see pseudocode) that satisfy fails when presented with empty input, so it is futile to write predicate functions that would recognize such input.

Examples

Run this code
# 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

Run the code above in your browser using DataLab