我是Haskell的新手,我正在尝试从输入中获取值列表,并从列表中每行打印一个项目.
func :: [String] -> IO ()
Run Code Online (Sandbox Code Playgroud)
当列表大小只为1时,我无法弄清楚如何打印列表中的项目.
func [] = return ()
func [x] = return x
Run Code Online (Sandbox Code Playgroud)
我在尝试编译文件时收到此错误消息:
Couldn't match expected type `()' with actual type `String'
In the first argument of `return', namely `x'
In the expression: return x
Run Code Online (Sandbox Code Playgroud)
我完全失去了,我尝试过搜索,但没有找到任何东西.谢谢!
你可以使用forM_这个:
func :: [String] -> IO ()
func l = forM_ l putStrLn
Run Code Online (Sandbox Code Playgroud)
如果您想直接编写自己的版本,则会遇到一些问题.
对于空列表,您无需做任何事情,只需创建一个值IO (),您可以使用return返回.
对于要输出行的非空列表putStrLn,然后处理列表的其余部分.非空列表的形式为x:xs,其中x是列表和头xs的尾部.您的第二个模式与单元素列表匹配.
func [] = return ()
func (x:xs) = putStrLn x >> func xs
Run Code Online (Sandbox Code Playgroud)
func = mapM_ putStrLn
Run Code Online (Sandbox Code Playgroud)
mapM_putStrLn对列表的每个元素应用monadic函数,并丢弃返回值.
小智 7
你实际上并没有尝试打印任何东西,你使用putStr.尝试类似的东西
print [] = return ()
print (x:xs) = do
putStr x
print xs
Run Code Online (Sandbox Code Playgroud)