Newsgroups: comp.lang.lisp
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!news2.near.net!howland.reston.ans.net!vixen.cso.uiuc.edu!uwm.edu!fnnews.fnal.gov!gw1.att.com!nntpa!ssbunews!iexist!not-for-mail
From: clarisse@iexist.flw.att.com (55437-olivier clarisse(haim)463)
Subject: Re: Lisp Question
Message-ID: <DA4zvD.8o0@ssbunews.ih.att.com>
Originator: clarisse@tenet
Sender: clarisse@iexist (55437-olivier clarisse(haim)463)
Nntp-Posting-Host: tenet.flw.att.com
Organization: AT&T
References:  <3ri5nq$fgc$1@mhafc.production.compuserve.com>
Date: Wed, 14 Jun 1995 00:26:01 GMT
Lines: 59


In article <3ri5nq$fgc$1@mhafc.production.compuserve.com>, Larry Putnam, Jr. <76274.72@CompuServe.COM> writes:
|> I have a couple of questions about LISP:
|> 
|> First, is there a way to do copy-by-value in LISP?  Specifically, 
|> I don't want the new object to share anything with the old 
|> object.  I would like to be able to do the copy-by-value even for 
|> objects (user-defined) that have sequences that contain 
|> sequences.  Of course, I could write a copy-object procedure for 
|> each object but I was hoping for something more elegant.
|> 
(apropos "COPY-" "COMMON-LISP")   ;Available COPY- things.

;;; For reasonable size objects that print readably
(defmethod copy-all (object &rest options)
  (read-from-string (apply #'write-to-string object :readably t options)))

(setq *print-level* 4)                 ;Limit print level.
(copy-all '#1=#(CLOS #1#) :circle t)   ;Circularities suspected.

;;; Then on user defined classes that need to print readably:
(defmethod print-object ((frog frog) stream)
  (cond (*print-readably*
         (write "#." :stream stream :escape nil :circle nil)
         (print-object `(make-instance 'frog :legs ,(frog-legs frog))
		       stream))
	(t
	 (call-next-method)))

;;; For more efficient copying, the designer of a class only knows
;;; how to copy it. Therefore COPY-OBJECT is defined on each class.
;;; Example for lists, sequences and frogs with no circularities:
(defmethod copy-object (object)
  object)

(defmethod copy-object ((object cons))
  (cons (copy-object (first object)) (copy-object (rest object))))

(defmethod copy-object ((seq sequence))
  (loop with cseq = (copy-seq seq)
	for c across cseq as n upfrom 0
	do (setf (elt cseq n) (copy-object c))
	finally (return cseq)))

(defmethod copy-object ((frog frog))
  (make-instance 'frog :legs (copy-object (frog-legs frog))))

|> Also, are there procedures to translate strings to integers or 
|> floats?  I could write something myself, but I imagine there is 
|> some standard procedure call for this.
|> 
;;; See READ-FROM-STRING and COERCE

(coerce (read-from-string "1234") 'float)
-- 
----------------
Olivier Clarisse	     "Languages are not unlike living organisms
Member of Technical Staff     can they adapt and improve to survive?"
AT&T Bell Laboratories
