Convert an Exact-Rational to an Integer in Racket

152 views Asked by At

I am writing a function in typed/racket to convert a list of Integers (0 or 1) representing a hexadecimal value to a decimal (Integer).

The function :

#lang typed/racket
(: to-decimal (-> (Listof Integer) Integer))
(define (to-decimal hex-values)
  (for/fold
          ([index : Integer 0]
           [result : Integer 0]
           #:result result)
          ([v : Integer (reverse hex-values)])
          (values (add1 index) (+ result (* v (expt 2 index))))))

This fails to type check. The expression (+ result (* v (expt 2 index))) gives me this error type mismatch expected: Integer given: Exact-Rational.

I know that Integers are a subset of Exact-Rational (source). Is there any way I can make my code type check ? Maybe by converting the value returned by the failing expression to Integer ?

Thanks a lot

1

There are 1 answers

0
Prygan On

(I share the answer that I found)

As index as been marked as Integer, it can be either positive, null or negative integer. As a consequence,(expt 2 index) can return a rational (if index is negative for example).

If index is marked as a Nonnegative-Integer, the function type check.