Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Haskell type conversions: converting a String to Int

2 min read

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'
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
Prelude> read "34"::Int
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
Prelude> read "34"::Int

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus