Home > other >  How can I make this code to work with the Integer- > Int type signature?
How can I make this code to work with the Integer- > Int type signature?

Time:10-25

This code is working with the Int- > [Int] type signature, but I have to solve it with Integer -> [Int] type signature. What do I have to change to make it work?

toBin :: Int -> [Int]
toBin n 
    | n == 0 = []
toBin n  =   [n `mod` 2]    toBin (n `div` 2) 

CodePudding user response:

You can use fromIntegral :: (Integral a, Num b) => a -> b to convert an Integer (or any Integral type) to an Int (or any Num type):

toBin :: Integer -> [Int]
toBin 0 = []
toBin n = [fromIntegral (n `mod` 2)]    toBin (n `div` 2)

If n is an Integer, than n `mod` `2 is an Integer as well. We can not use n `mod` 2 as element of a list, since the return type is [Int], so a list of Ints. We thus need to convert the Integer to an Int such that the type of the elements is correct, and we can convert an Integer to the corresponding Int (given the Integer can be represented by an Int) with fromIntegral.

  • Related