Haskell User Input
User input is text or a character that a person types while a program runs. Haskell actions such as getLine and getChar collect that input.
getLine reads a whole line
The typed line is Ana. The program greets that name.
main :: IO ()
main = do
name <- getLine
putStrLn ("Hello, " ++ name)getChar reads one character
The typed character is A. print shows it in its Char form.
main :: IO ()
main = do
letter <- getChar
print letterread turns text into a number
The typed line is 21. read turns it into a number, and the program doubles it.
main :: IO ()
main = do
text <- getLine
let number = read text :: Int
print (number * 2)Example
main :: IO ()
main = do
name <- getLine
ageText <- getLine
let age = read ageText :: Int
putStrLn name
print (age + 1)Key points
- getLine: an action that reads one line of typed text as a String.
- getChar: an action that reads one typed character.
- Typed text: input arrives as text, even when the person types digits.
- read: a function that turns valid number text into a number.
- Valid input: the typed text must match the type that read is asked for.
- Line by line: each getLine action reads one line, in the order the actions run.
In this example, the typed lines are Sam and 19. The first getLine binds Sam to name, and the second binds the text 19 to ageText. read turns that text into the number 19, so the last action prints 20.
Note
getLine gives the line without the Enter key press at its end.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does getLine give the program?