On 12/1/2018 12:28 PM, hashim muqtadir wrote:
But this doesn't typecheck:

> (for ([x (in-list '("123" "432" "234"))])
    (define num (string->number x))
    (unless num
      (error "Not a number"))
    (define double (* num 2))
    (display (format "~s" double)))
. Type Checker: type mismatch
  expected: Number
  given: (U Complex False) in: num

Am I missing something here?

That string->number returns #f if it fails - and if num is #f then (* num 2) is meaningless.

The type error is telling you where you will run into the problem:
  expected: Number
  given: (U Complex False) in: num

You know that execution won't reach the multiplication if num is #f, but the compiler doesn't.

I'm not any kind of typed Racket wizard, but the type error goes away if you explicitly use a conditional:
      ([false? num]
       (error "Not a number") )
       (define double (* num 2))
       (display (format "~s" double)) ))

If you use LET rather than the internal define, you can use IF instead.
    (if num
      (let ((double (* num 2)))
        (display (format "~s" double)))
      (error "Not a number")


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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to