Migrating from Python to Racket (Regular Expressions Question)

Status
Not open for further replies.

ProgrammingWolf

Smack-Fu Master, in training
53
Hi All,

I'm attempting to learn Racket, and in the process am attempting to rewrite a Python filter. I have the following pair of functions in my code:

Code:
def dlv(text):
    """
    Returns True if the given text corresponds to the output of DLV
    and False otherwise.
    """
    return text.startswith("DLV") or \
           text.startswith("{") or \
           text.startswith("Best model")

def answer_sets(text):
    """
    Returns a list comprised of all of the answer sets in the given text.
    """
    if dlv(text):
        # In the case where we are processing the output of DLV, each
        # answer set is a comma-delimited sequence of literals enclosed
        # in {}
        regex = re.compile(r'\{(.*?)\}', re.MULTILINE)
    else:
        # Otherwise we assume that the answer sets were generated by
        # one of the Potassco solvers. In this case, each answer set
        # is presented as a comma-delimited sequence of literals,
        # terminated by a period, and prefixed by a string of the form
        # "Answer: #" where "#" denotes the number of the answer set.
        regex = re.compile(r'Answer: \d+\n(.*)', re.MULTILINE)
    return regex.findall(text)

From what I can tell the implementation of the first function in Racket would be something along the following lines:

Code:
(define (dlv-input? text)
  (regexp-match? #rx"^DLV|^{|^Best model" text))

Which appears to work correctly. Working on the implementation of the second function, I currently have come up with the following (to start with):

Code:
(define (answer-sets text)
  (cond
    [(dlv-input? text) (regexp-match* #rx"{(.*?)}" text)]))

This is not correct, as regexp-match* gives a list of the strings which match the regular expression, including the curly braces. Does anyone know of how to get the same behavior as in the Python implementation? Also, any suggestions on how to make the regular expressions "better" would be much appreciated.
 
D

Deleted member 43669

Guest
I think you want to read:

match-select specifies the collected results. The default of car means that the result is the list of matches without returning parenthesized sub-patterns. It can be given as a ‘selector’ function which chooses an item from a list, or it can choose a list of items. For example, you can use cdr to get a list of lists of parenthesized sub-patterns matches, or values (as an identity function) to get the full matches as well. (Note that the selector must choose an element of its input list or a list of elements, but it must not inspect its input as they can be either a list of strings or a list of position pairs. Furthermore, the selector must be consistent in its choice(s).)

from http://docs.racket-lang.org/reference/r ... /base..rkt)._regexp-match*)) , and the examples below.
 
Status
Not open for further replies.