match_s {parcr}R Documentation

Identifying and processing a string and producing custom output

Description

match_s matches a string using a function and returns a desired object type.

Usage

match_s(s)

Arguments

s

a string-parsing function.

Details

This parser short-cuts the pattern satisfy(b) %using% f. With match_s you do not have to write separate predicate and processing functions b and f when identification and parsing can be done with a single string parsing function s.

The function s will be given a non-empty single-element character vector as its argument, so you don't have to test for empty input, like character(0). These two facts also often simplify further processing with the string functions like grep, regmatches and those from the stringr package. The function s can return any R-object when succeeding, but to signal failure to the parser it must return the empty list(). Note that list() output from s will be turned into a marker object, the internal object to mark failure, by match_s(), see failed().

Value

A parser.

Pseudocode

match_s(s)(x):
  if x==null then fail()(x)
  else if s(x[1]) then succeed(s(x[1]))(x[-1]) else fail()(x)

Examples

expect_integers <- function(x) {
  m <- gregexpr("[[:digit:]]+", x)
  matches <- regmatches(x,m)[[1]]
  if (length(matches)==0) {
    # this means failure to detect numbers where we expected them
    return(list())
  } else {
    return(as.numeric(matches))
  }
}

match_s(expect_integers) ("12 15 16 # some comment") # success
match_s(expect_integers) ("some text") # failure


[Package parcr version 0.5.1 Index]