Haskell type conversions: converting a String to Int
2 min read
2 min read
putStrLn "Hello there!"to print an entire line which would correspond to something like System.out.println("Hello there!") in Java or
putStr "Hello"to just print the string (in Java: System.out.print("Hello")).
import CharLoading this into your Haskell interpreter (I'm using ghc, ghci) and calling the function will return the following:
getInt :: Char -> Int
getInt x = digitToInt x
*Main> getInt '3'This works perfectly until you have just a single digit, i.e. numbers from 0 to 9, but what if the user types in 12?? It won't work because it is no more a single char, but would already be a String. So it was not usable for my battleship game since the board of my game may be of variable length (i.e. the internal matrix representation of the board may be of size 15x15). Moreover using getChar for reading from the input turned out to be not that suitable.
3
Prelude> read "4"::IntThat was perfectly what I've been searching for. It takes a String and converts it into an Int. And you could even do the following
4
Prelude> read "34"::Int
34
Prelude> read "4"::Int
4
Prelude> read "34"::Int
34