help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: why are there [v e c t o r s] in Lisp?


From: Pascal J. Bourguignon
Subject: Re: why are there [v e c t o r s] in Lisp?
Date: Sat, 17 Oct 2015 03:55:15 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

Emanuel Berg <embe8573@student.uu.se> writes:

> Random832 <random832@fastmail.com> writes:
>
>> The thing is, if you can car a string people will
>> wonder why you can't cdr it. And with mutable
>> objects it's hard to make cdr work right. (fsvo
>> "right")
>
> You can't `car' a string or do anything with it that
> requires it to be a list, because it isn't. If you try
> to car it, the string will fail the `listp' test.
> But because it is natural to think of strings as lists
> of chars, perhaps from the C days of, say
>
>     char *str = malloc(strlen(argv[argc - 1]));
>
> or actually because it is normal for humans to think
> of strings that way, it should be pointed out - and
> now that has happened - that the "string" syntax isn't
> a shorthand for creating lists of chars.

In emacs lisp it'd be difficult to do it, but in Common Lisp it's
trivial:

(defpackage "EB-LISP"
  (:use "COMMON-LISP")
  (:shadow "CAR" "CDR" "CONSP" "LISTP")
  (:export . #.(let ((syms '()))
                 (do-external-symbols (s "COMMON-LISP" syms)
                   (push (symbol-name s) syms)))))
(in-package "EB-LISP")

(defun car (x)
  (if (vectorp x)
      (aref x 0)
      (cl:car x)))

(defun cdr (x)
  (if (vectorp x)
      (if (< 1 (length x))
          (make-array (1- (length x))
                      :element-type (array-element-type x)
                      :displaced-to x
                      :displaced-index-offset 1)
          '())
      (cl:cdr x)))

(defun consp (x)
  (or (vectorp x) (cl:consp x)))

(defun listp (x)
  (or (vectorp x) (cl:listp x)))


(defpackage "EB-LISP-USER"
  (:use "EB-LISP"))
(in-package "EB-LISP-USER")

(loop :for string := "hello world" :then (cdr string)
       :while string
       :collect (car string))
;; --> (#\h #\e #\l #\l #\o #\  #\w #\o #\r #\l #\d)



Instead, in emacs-lisp you can prefix your symbols: eb-lisp-car
eb-lisp-cdr etc…  (and you have to implement more things yourself, since
there are no displaced arrays, etc).

-- 
__Pascal Bourguignon__                 http://www.informatimago.com/
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk


reply via email to

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