user4929787
user4929787

Reputation:

How can I use getLine or getChar in haskell?

I'm trying to get from my console a string or just a char and store into a variable.

I tried to use:

> let x = getChar
> x
> c -- for getting a char.

But nothing is stored (same for getLine) how can I do?

Upvotes: 2

Views: 11027

Answers (4)

Rafa Moyano
Rafa Moyano

Reputation: 181

You need to bind it to a variable using <-, the result of an action is being bound:

*Main> variable <- getLine 
 hello      
*Main> putStrLn variable 
 hello
*Main> anotherChar <- getChar
a*Main> 
*Main> putChar anotherChar 
a*Main> 

Function getLine has type IO String and getChar has type IO Char.

Upvotes: 0

granmirupa
granmirupa

Reputation: 2790

Reading from console, maybe is not very useful. However you should use <- construct.

For example (without " is good too) :

>myString <- getLine
>"Hello world" 

or

>myChar <- getChar
>c

For more I suggest to read here

Upvotes: 1

chepner
chepner

Reputation: 530970

The type of getChar is IO Char. It is not a function that returns a Char; it is an IO action that, when executed, returns a Char. (While subtle, this distinction is crucial to understanding how Haskell performs IO with pure functions.)

The line

let x = getChar

just binds the name x to the same IO action (which you can see by subsequently typing :t x in GHCi). Typing x then executes that action; GHCI waits for you to type a character, then it immediately returns that character.

To use getChar in a program, you need to use it within an IO monad, with something like

main = do ch <- getChar
          print ch

or

main = getChar >>= print

Upvotes: 6

jamshidh
jamshidh

Reputation: 12060

Here is a sample

main = do
    x <- getLine
    putStrLn $ "Here is the string you typed in: " ++ x

Upvotes: 2

Related Questions