Page 1 of 1
C's strcmp to CLISP
Posted: Thu Dec 23, 2010 6:52 am
by kurlsoft
Hi all,
could anyone help me out with the translation of C's strcmp() to CLISP.
C source:
Code: Select all
int strcmp_i(char *s, char *t)
{
for(; *s==*t && *s!='\0'; s,t);
return(*s - *t);
}
Thanks a lot.
Re: C's strcmp to CLISP
Posted: Thu Dec 23, 2010 8:27 am
by ramarren
What do you mean by translation? Common Lisp is, unlike C, a strongly typed language with, usually, automatic memory management. They are too different for there to be any direct correspondence.
Re: C's strcmp to CLISP
Posted: Fri Dec 24, 2010 1:09 pm
by nuntius
One big difference between C strings and Lisp strings is that the former use a null byte to mark end-of-string while the latter store an explicit length. Anyway, here's some code to chew over. Note that
t is a predefined symbol in the CL package; thus its usually easier to use a different name than to shadow it in another package.
Code: Select all
(defun strcmp-i (str1 str2)
"one approach towards implementing strcmp_i (incomplete)"
;; returns the index of the first character which was not the same
;; could be used below instead of string-not-equal
(loop for c1 across str1
and c2 across str2
and i = 1 then (1+ i)
while (char= c1 c2)
finally (return i))
1)
(defun strcmp-i2 (str1 str2)
"a more idiomatic strcmp_i (complete)"
(let ((index (string-not-equal str1 str2)))
(cond ((not index)
0)
((= index (length str1))
-1)
((= index (length str2))
1)
(t (- (char-code (char str1 index))
(char-code (char str2 index)))))))
Re: C's strcmp to CLISP
Posted: Sat Dec 25, 2010 7:21 pm
by kurlsoft
Thank you nuntius ,Your code snippet seems to solve the problem, I will go through it carefully, and see how I could implement it recursively.
Thank you again.
Re: C's strcmp to CLISP
Posted: Sat Dec 25, 2010 7:42 pm
by kurlsoft
hi Ramarren,
Than you for the reply.
I mean converting strcmp(), such that,
(strcmp 'abc 'abbbe) => 1 : here last character (3rd character = c) in 'abc is greater than b(3rd character) in 'abbbe so => 1.
(strcmp 'abc 'abcd) => -1 : here the null character in 'abc is inferious to d(4rd character) in 'abcd so => -1.
(strcmp 'abc 'abc) => 0 : here the last characters are equal so => 0.
Thank you.
Re: C's strcmp to CLISP
Posted: Sun Dec 26, 2010 3:02 pm
by gugamilare
Note that 'abc is not a string in Lisp, it is a symbol. The denotation of strings in Lisp is between quotes, "abc".
If you want to work with symbols, convert them to strings using symbol-name.
Re: C's strcmp to CLISP
Posted: Sun Dec 26, 2010 7:17 pm
by Warren Wilkinson
I just wanted to chime in that common lisp has a few routines for string-comparison (e.g. string-equal and string<). Just making sure you're porting strcmp for practice and not necessity.