简体   繁体   English

Haskell,使用用户输入创建列表

[英]Haskell, Create list with user input

Hello I need to create a list from the user input and stop when "END" is detected. 您好,我需要根据用户输入创建一个列表,并在检测到“ END”时停止。 I'm learning Haskell so it's a bit confuse with the IO. 我正在学习Haskell,因此与IO有点混淆。

I have this code to recursivly add the input in a list and when "END" is write by the user it give the list 我有这段代码可以将输入递归添加到列表中,并且当用户写入“ END”时,它将给出列表

getList :: [String] -> IO [String]
getList list =  do line <- getLine
                   if line ==  "END"
                      then return list
                      else getList (line : list)

and I try to catch the result and print it in this function, it already take two parameter that I didn't code already. 我试图捕获结果并在此函数中打印出来,它已经带有两个我尚未编写代码的参数。

checkDebruijn :: Int -> String -> IO ()
checkDebruijn sequence alphabet  = do
    print (getList [])

And I call it in the main to test it 我称它为主要测试

main :: IO ()
main = do
  print (checkDebruijn 0 "")

And I have this error : 我有这个错误:

No instance for (Show (IO [String]))
        arising from a use of ‘print’
    • In a stmt of a 'do' block: print (getList [])
      In the expression: do print (getList [])
      In an equation for ‘checkDebruijn’:
          checkDebruijn sequence alphabet = do print (getList [])
  |
7 |     print (getList [])
  |     ^^^^^^^^^^^^^^^^^^

I see that print is : print :: Show a => a -> IO () So I don't understand why it wouldn't compile. 我看到print是:print :: Show a => a-> IO()所以我不明白为什么它不能编译。 For me IO is an action that the compiler do. 对我而言, IO是编译器执行的操作。 So getList :: [String] -> IO [String] IO [String] is when the compiler do an action and return a [String] ? 所以getList :: [String]-> IO [String] IO [String]是编译器执行操作并返回[String]时的时间吗?

As you say, print has type 就像您说的那样, print具有类型

print :: Show a => a -> IO ()

and getList [] has type IO [String] , so for print (getList []) to typecheck there must be a Show instance for IO [String] . 并且getList []类型为IO [String] ,因此要进行print (getList [])进行类型检查,必须有一个IO [String]Show实例。 There is no such instance, which causes the error. 没有这样的实例,它会导致错误。

There is a Show instance for [String] however, so you can call print on the list returned by executing getList [] . 但是, [String]有一个Show实例,因此您可以在执行getList []返回的列表上调用print You can use do notation to bind the result to call print on it: 您可以使用do表示法将结果绑定到其上调用print:

checkDebruijn sequence alphabet  = do
    result <- (getList [])
    print result

Your main should look like: 您的主体应如下所示:

main = getList [] >>= print

where: 哪里:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

Or alternatively: 或者:

main = do
  xs <- getList []
  print xs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM