I came to the following result as conversion function :

#lang typed/racket
(: string2value (-> String Integer))
(define (string2value astring)
  (define (fun [val : Char] [res : Integer])
    (+ (* 10 res) (- (char->integer val) 48)))
  (foldl fun 0 (string->list astring))
)
(print (string2value "12345"))



On Tuesday, February 11, 2020 at 11:34:16 AM UTC+1, Alain De Vos wrote:
>
> I tried the following function to conver a String to an Integer.
>
> #lang typed/racket
> (: myconversion (-> String Integer))
> (define (myconversion str)
>   (string->number str))
>
> The error given is :
> Type Checker: type mismatch
>   expected: Integer
>   given: (U Complex False) in: (string->number str)
>
> I guess this is because a number is not an Integer.
>
> How to proceed?
>
> I found the following code on internet , but this looks like a real 
> overkill for this simple problem ,
>
> (: numerical-char->integer (-> Char
>                                Integer))(define (numerical-char->integer char)
>   (let ([num (- (char->integer char) 48)]) ; 48 = (char->integer #\0)
>     (if
>      (or (< num 0) (> num 9))
>      (raise 'non-numerical-char #t)
>      num)))
> (: string->integer (-> String
>                        Integer))(define (string->integer str)
>   (let ([char-list (string->list str)])
>     (if (null? char-list)
>         (raise 'empty-string #t)
>         (foldl
>          (λ([x : Integer] [y : Integer])
>            (+ (* y 10) x))
>          0
>          (map numerical-char->integer char-list)))))
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/racket-users/3e58a927-c05a-4688-984c-1750fb014624%40googlegroups.com.

Reply via email to