mchu...@gmail.com writes:
> Sometimes people write compound sentences which have two statements in
> one sentence.
>
> For example I like you and you like me. I would like you to write a
> function called BREAK_COMP that will accept a sentence and if the the
> sentence is a compound sentence return a list containing a list for
> each statement. If the sentence is not a compound sentence return a
> list of the sentence within a list.
>
> Assumptions:
> You can assume the following:
> 1. AND is the only word that can create compound sentences.
> 2. Any time that AND is used it is a compound sentence.
> 3. A compound sentence can only have 1 AND in it.
>
> Sample Output:
> Here is sample output for the function.
> Break 10 [14]> (BREAK_COMP '(I like you))
> ((I LIKE YOU))
> Break 10 [14]> (BREAK_COMP '(I like you and you like me))
> ((I LIKE YOU) (YOU LIKE ME))
>
>
> Would anyone care to show me one way they would implement this? The
> program itself is supposed to be quite short. I have never used lisp
> until now and I was only exposed to it a couple weeks ago.
You start with a grammar, and then write a parser.
From your rules, we have the following grammar:
sentence ::= { word } [ 'AND' {word } .
word ::= anything but 'AND'.
To keep it simple, I'll use the lisp reader as a scanner; the input to my
parser will be a list of symbol tokens.
(defun parse-sentence (tokens)
(let ((first-statement
(loop
:while (and tokens (not (eq 'and (first tokens))))
:collect (pop tokens))))
(if tokens
(progn
(pop tokens) ; eat AND.
(when (find 'and tokens)
(error "Not a sentence (two AND)"))
(list first-statement tokens))
(list first-statement))))
(defun break_comp (tokens)
(parse-sentence tokens))
cl-user> (break_comp '(hello world))
((hello world))
cl-user> (break_comp '(hello world and good bye tony))
((hello world) (good bye tony))
cl-user> (break_comp '(hello world and good bye tony and that's all))
> Debug: Not a sentence (two AND)
--
__Pascal Bourguignon__
http://www.informatimago.com/
A bad day in () is better than a good day in {}.