guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Palindromes and pattern matching


From: Panicz Maciej Godek
Subject: Palindromes and pattern matching
Date: Tue, 18 Sep 2012 22:08:11 +0200

Howdie,
I've been learning the refal language recently
(http://refal.botik.ru/book/html/ )
and I've been wondering, if there's any way
to simulate the behaviour of the refal's pattern
matcher using the Andrew K. Wright's/Alex Shinn's
pattern matcher for Scheme. Namely,
the Refal tutorial presents a following definition
of a palindrome:

<quote>
1. An empty string is a palindrome.
2. A string of one symbol is a palindrome.
3. If a string starts and ends with the same symbol, then it is a
palindrome if and only if the string which remains after the removal
of the first and the last letters is a palindrome.
4. If none of the above are applicable, the string is not a palindrome.
</quote>

The tutorial also presents the Refal code that
implements the above conditions to construct the
predicate that states whether a given object is a
palindrome:

<quote>
Pal { = True;
     s.1 = True;
     s.1 e.2 s.1 = <Pal e.2>;
     e.1 = False;  }
</quote>

The notation is a little bit funny, but it should be
comprehensible. The <function args> represents
application of a function, and the empty string
isn't mentioned explicitly.

I don't know whether the Scheme's pattern matcher
has any notation for getting the last element of a list.
At first, I thought that maybe it could be done using
the unquote-splicing operator, so the equivalent code
would look like this:
(define (palindrome? l)
  (match l
    (() #t)
    ((s1) #t)
    (`(,s1 ,@e2 ,s1) (palindrome? e2))
    (else #f)))

but apparently this code doesn't work.
Is there a clean and simple way to achieve this using
the aforementioned pattern matcher?

Best regards,
M.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]