Home > Net >  Writing a function to take character representing number and return corresponding integer
Writing a function to take character representing number and return corresponding integer

Time:10-26

So far I have got this. I understand that I need to instantiate char to int but I am wondering if there is a way to say if a value as a character is entered 0-9 it will provide the integer value.

char_to_int :: Char -> Integer
char_to_int c = digitToInt c

main = do
    let number = '0'
    putStrLn "The number : "
    print (number)
    putStrLn "Integer equivalent to character entered"
    print ( char_to_int number)

I am getting this error:

 |
6 | char_to_int c = digitToInt c
 |                 ^^^^^^^^^^
Failed, no modules loaded.

Any help would be appreciated :)

CodePudding user response:

You need to import the function. Furthermore it converts a Char to an Int, and thus only works for a single character:

import Data.Char (digitToInt)

char_to_int :: Char -> Int
char_to_int = digitToInt

But since you only here make an extra reference to the digitToInt function, you can use that directly:

import Data.Char (digitToInt)

main :: IO ()
main = do
    let number = '0'
    putStrLn "The number : "
    print (number)
    putStrLn "Integer equivalent to character entered"
    print (digitToInt number)
  • Related