typed-racket

Why doesn't `integer?` only succeed for things of type Integer?


It seems like integer? can succeed for ... non-integers? Why doesn't this code type-check?

#lang typed/racket

(define x : Real 134)

(define y : Integer (cond [(integer? x) x]
                          [else (error "not an integer")]))

Solution

  • You're absolutely right, the integer? predicate doesn't just succeed for things of type Integer, it also succeeds for inexact reals like 3.0. You probably wanted to use the predicate exact-integer?, instead:

    #lang typed/racket
    
    (define x : Real 134)
    
    (define y : Integer (cond [(exact-integer? x) x]
                              [else (error "not an integer")]))
    

    This code type-checks and runs.

    The same goes for nonnegative-integer?, use instead exact-nonnegative-integer?.