简体   繁体   English

Haskell:[String]到IO()

[英]Haskell: [String] to IO ()

I am new to Haskell and I am trying to get a list of values from input and print one item out from the list each line. 我是Haskell的新手,我正在尝试从输入中获取值列表,并从列表中每行打印一个项目。

func :: [String] -> IO ()

I am having trouble trying to figure out how to print out the item in the list, when the list size is just 1. 当列表大小只为1时,我无法弄清楚如何打印列表中的项目。

func [] = return ()  
func [x] = return x

I am getting this error message when trying to compile the file: 我在尝试编译文件时收到此错误消息:

Couldn't match expected type `()' with actual type `String'
    In the first argument of `return', namely `x'
    In the expression: return x

I am completely lost and I have tried searching but haven't found anything. 我完全失去了,我尝试过搜索,但没有找到任何东西。 Thanks! 谢谢!

You can use forM_ for this: 你可以使用forM_

func :: [String] -> IO ()
func l = forM_ l putStrLn

If you want to write your own version directly, you have some problems. 如果您想直接编写自己的版本,则会遇到一些问题。

For the empty list, you have nothing to do but create a value of IO () , which you can do with return. 对于空列表,您无需做任何事情,只需创建IO ()的值,您可以使用return执行此操作。

For the non-empty list you want to output the line with putStrLn and then process the rest of the list. 对于非空列表,您希望使用putStrLn输出行,然后处理列表的其余部分。 The non-empty list is of the form x:xs where x is the head of the list and xs the tail. 非空列表的形式为x:xs其中x是列表的头部和xs的尾部。 Your second pattern matches the one-element list. 您的第二个模式与单元素列表匹配。

func [] = return ()
func (x:xs) = putStrLn x >> func xs
func = mapM_ putStrLn

mapM_mapM_putStrLn函数应用于列表的每个元素,并丢弃返回值。

you actually aren't trying to print anything, you use putStr for that. 你实际上并没有尝试打印任何东西,你使用putStr。 try something like 尝试类似的东西

print [] = return ()
print (x:xs) = do
                 putStr x
                 print xs

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

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