convert from string to ints 
Author Message
 convert from string to ints

I have an application in which I am using Elk-2.2 as an extension language.
I was wondering if anybody knows of a better way to convert strings to
integers and floats than this (mind you I am just a beginning lisp hacker):
;;
;; Define function to convert string to integer.
;; There has got to be a better way of doing this, but being
;; a beginning lisp programmer, I don't know it.
;;
(define atoi
  (lambda (str)
    (let ( (val 0) )
      (for-each (lambda (a)
                  (set! val (+ (* 10 val) (- (char->integer a) 48))))
                (string->list str)
                )
      val)))

;;
;; Define function to convert string to float.
;; There has got to be a better way of doing this, but being
;; a beginning lisp programmer, I don't know it.
;;
(define ftoa
  (lambda (val)
    (let ((p (open-output-string)))
      (write val p)
      (get-output-string p))))

Thanks.
- pat



Thu, 14 Nov 1996 20:39:52 GMT  
 convert from string to ints

   I have an application in which I am using Elk-2.2 as an extension language.
   I was wondering if anybody knows of a better way to convert strings to
   integers and floats than this (mind you I am just a beginning lisp hacker):

Hmmm, I haven't used Elk recently, but the answer to your question is
an emphatic, "Yes, there's a *much* easier way in Scheme!"

(string->number "123")             => 123
(string->number "123.45")  => 123.45

R^4RS has this marked as an "essential procedure," so I'd expect Elk
has it.  If not, :-/ it can be trivially implemented using string
ports from Slib:

(require 'string-port)

(define (string->number s)
  (call-with-input-string s (lambda (port) (read port))))

In the spirit of C, a language with which your previous post implies
you are familiar ;-), the above does no error checking.  A slightly
safer version is given below:

(define (string->number s)
  (call-with-input-string
   s
   (lambda (port)
     (let ((result (read port)))
       (if (number? result)
           result
           #f)))))

Have fun with Scheme!

   Thanks.
   - pat

--
// Kaelin Colclasure ---------------------------------------------------------

// Voice: (314)567-8463                      717 Office Parkway
//   Fax: (314)432-5391                      St. Louis, MO 63141



Fri, 15 Nov 1996 06:55:56 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. converting floats, ints byte arrays

2. Converting floats to ints

3. Summary: Converting floats to ints quickly in C

4. FPU STUFF (CONVERTING FROM REAL TO INTS)

5. Converting large ST ints to C longs

6. Ints/Floats to Strings

7. string from two ints

8. comparing strings and ints

9. string from two ints

10. How to convert binary string to char string ?

11. CIN: Converting a C String to a LabVIEW String

12. Using scan from string to convert a string into a number

 

 
Powered by phpBB® Forum Software