Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.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中从键盘读取字符串_Haskell - Fatal编程技术网

在haskell中从键盘读取字符串

在haskell中从键盘读取字符串,haskell,Haskell,我想从键盘上读取字符串,但我不知道为什么不起作用,我尝试了很多方法,但都不起作用!有人能帮我或给我一个主意吗 type Polinom = [Int] scriePolinom :: Polinom -> String .... main = do a<-getLine --let a=[2,-5,1] scriePolinom a 类型Polinom=[Int] scriePolinom::Polinom->String .... main=

我想从键盘上读取字符串,但我不知道为什么不起作用,我尝试了很多方法,但都不起作用!有人能帮我或给我一个主意吗

type Polinom = [Int]    
scriePolinom :: Polinom -> String
....
main = do  
    a<-getLine
    --let a=[2,-5,1] 
    scriePolinom a
类型Polinom=[Int]
scriePolinom::Polinom->String
....
main=do

a将该行解析为相应的数据:

import Data.List
parseIntList :: String -> [Int]
parseIntList s = [read x :: Int | x <- words s]

type Polinom = [Int]    
scriePolinom :: Polinom -> String
....
main = do  
    a <- getLine
    let intlist = parseIntList a
    putStrLn $ scriePolinom intlist
导入数据。列表
parseIntList::String->[Int]
parseIntList s=[读取x::Int | x字符串
....
main=do
A.
这告诉你
getLine
总是给你一个
String
类型的值(在做了一些不纯的I/O操作之后,在这种情况下,等待用户在键盘上输入一些东西,直到按enter键)。这很有意义:一个字符串,也称为

Prelude> :info String   -- you can also write :i String
type String = [Char]    -- Defined in ‘GHC.Base’
…字符列表。这些字符只是用户键入的确切字符/键。通常,这些字符可能无法正确描述
Polinom
–例如,如果用户输入
34958oiyq4ulbwre
,会发生什么

您需要做的是尝试将输入字符串解析为一个更有意义的类型值,如
Polinom
。如何做取决于您实际期望的输入形式。如果用户应该对系数使用正常的Haskell语法,例如
[2,-5,1]
,则可以使用标准解析器:

或者,如果您期望的只是一系列以十进制表示的空格分隔的数字,您可以首先将这些数字拆分为单词,然后分别阅读:

Prelude> scriePolinom . map read $ words "2 -5 1"
"[2,-5,1]"
要在可执行程序中使用它,可以使用
getLine
read
的现成组合:

main :: IO ()
main = do  
    a <- readLn
    putStrLn $ scriePolinom a
main::IO()
main=do
a,37字节

fl=[b |(a,b)
parseIntList::String->[Int]parseIntList s=[read x::Int | x“do”块中的最后一个语句必须是一个表达式a@Bob,您在IO monad上,所以您必须对它做些什么,主要是打印它,我将添加到答案中
main
需要有type
IO()
,但
scriePolinom a
具有类型
字符串
Prelude> scriePolinom . map read $ words "2 -5 1"
"[2,-5,1]"
main :: IO ()
main = do  
    a <- readLn
    putStrLn $ scriePolinom a