Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

Haskell type conversions: converting a String to Int

Today I just finished my battle-ship game written completely in functional programming (using Haskell). In order to have the user interact with your game you clearly have to write and read from the command-line. Writing is easy, just do something like

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")).
When reading from the keyboard you have functions like getChar for reading a single character or getLine to read the whole line (user has to press the return key to submit). The problem however is that in the first case (getChar) you get a Char datatype and in the second case you get a String. In order to do computations however (as in the case of my battleship game), you need to convert them into a numerical format. Now if you're a Haskell hacker, you'll probably laugh about that, but as a newbie I initially had to search for quite a bit in order to find the appropriate functions.
So my colleague Matthias found a function called digitToInt which basically converts a Char into an Int type.
import Char

getInt :: Char -> Int
getInt x = digitToInt x
Loading this into your Haskell interpreter (I'm using ghc, ghci) and calling the function will return the following:
*Main> getInt '3'
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.
So after searching for a bit I found out that you can use the "read" function defined in the Prelude for doing type conversions. The following commands (directly typed in the Haskell interpreter) return for instance these results:
Prelude> read "4"::Int
4
Prelude> read "34"::Int
34
That 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
Prelude> read "4"::Int
4
Prelude> read "34"::Int
34

Posts you might also be interested in..

Credits: Hoctro | Jack Book

4 Comments:

Anonymous said...

Thank you. Converting a string to integer in Haskell is exactly what I'm looking for.

Kay

Christopher Broos said...

NICE! I was seriously looking for this. Thanks a bundle mate.

Anonymous said...

Thanks..I was looking for that and it works..

Alechandrina said...

I love you...xD, this is just what I needed =)

Post a Comment