0 Replies - 1251 Views - Last Post: 06 June 2011 - 08:51 AM

#1 I X Code X 1  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 66
  • Joined: 28-July 10

[Lisp] Find the sum of all the integers in a number - Common Lisp

Posted 06 June 2011 - 08:51 AM

Description: This will work with any Common Lisp implementation; I used Allegro CL.In this snippet, it may not be the most direct path to achieve the desired goal, but the point is to show the different kind of conversions that can be done in common lisp: Integer-string, String-characters, Characters-string, String-integer.
(defun sum-digits (n)
  (setf *digits* (coerce (write-to-string n) 'list))
  (setf *strings* (loop for x in *digits*
                      collect (string x)))
  (format t "~a" (apply #'+ (loop for x in *strings*
        collect (parse-integer x)))))

;; This takes one integer as a parameter (54321)

;; We start by converting the integer to a string, using the write-to-string
;; function. We could of also used the pri n1-to-string/princ-to-string 
;; functions, but write-to-string let's us set a base, if we wanted to.

;; On the same line, we convert the string representation to characters.
;; To do this, we but send the string to a list (or array) of characters
;; using the coerce args 'list function.

;; On the third line we do a simple loop through our list of characters and
;; convert them back into a string; using (string x). The reason we want to
;; do this is because in common lisp to convert a character to an integer,
;; it must be a string.

;; Lastly, we loop thorough our list of now strings ("5" "4" "3" "2" "1")
;; and turn each string into an integer representation using (parse-integer).
;; Finally, we simply apply the addition function to each element and in the
;; list, and we have our result!


CG-USER(23): (sum-digits 54321)
15
NIL

CG-USER(24): (sum-digits 1337)
14
NIL


; Note: The NIL is just the return value of the format function. In CL, the
; last function is always returned. In this case it is format's NIL value.




Is This A Good Question/Topic? 0
  • +

Page 1 of 1