Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在haskell中使用getLine或getChar?_Haskell - Fatal编程技术网

如何在haskell中使用getLine或getChar?

如何在haskell中使用getLine或getChar?,haskell,Haskell,我正试图从控制台获取一个字符串或一个字符,并将其存储到变量中 我尝试使用: > let x = getChar > x > c -- for getting a char. 但是没有存储任何内容(getLine也是如此)我该怎么做呢?这里是一个示例 main = do x <- getLine putStrLn $ "Here is the string you typed in: " ++ x main=do 从控制台读取,可能不是很有用。但是,您应

我正试图从控制台获取一个
字符串
或一个
字符
,并将其存储到变量中

我尝试使用:

> let x = getChar
> x
> c -- for getting a char.
但是没有存储任何内容(getLine也是如此)我该怎么做呢?

这里是一个示例

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

从控制台读取,可能不是很有用。但是,您应该使用
getChar
的类型是
iochar
。它不是一个返回字符的函数;它是一个IO操作,执行时返回一个
Char
。(虽然这种区别很微妙,但对于理解Haskell如何使用纯函数执行IO至关重要。)

线路

let x = getChar
只需将名称
x
绑定到同一IO操作(您可以通过随后在GHCi中键入
:t x
看到)。键入
x
然后执行该操作;GHCI等待您键入一个字符,然后立即返回该字符

要在程序中使用
getChar
,您需要在IO monad中使用它,例如

main = do ch <- getChar
          print ch

您需要使用变量putStrLn variable将其绑定到一个变量 你好 *Main>anotherChar *Main>putChar另一个char a*Main>

函数getLine的类型是IO字符串,而getChar的类型是IO字符。

在本教程的不远之处,他们读到了一个字符:谢谢你的回答,它非常准确,但我要求直接从控制台使用。@user4929787(我想你指的是从内部使用它,
ghci
…如果我假设不正确,请告诉我!)试试
ch
let x = getChar
main = do ch <- getChar
          print ch
main = getChar >>= print
*Main> variable <- getLine 
 hello      
*Main> putStrLn variable 
 hello
*Main> anotherChar <- getChar
a*Main> 
*Main> putChar anotherChar 
a*Main>