Haskell:不能使用“map putStrLn”? [英] Haskell: can't use "map putStrLn"?

查看:125
本文介绍了Haskell:不能使用“map putStrLn”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ls = [banana,mango,橙色] 

main = do
map PutStrLn list_of_strings

这不起作用,我不明白为什么。

  ghc print-list.hs 
print- list.hs:3:0:
对于推断类型[IO()]'
,无法匹配预期类型'IO t'在表达式中:main
检查函数`main'

任何提示?我想这与地图返回一个列表有关,而不是一个值,但我没有找到一个简单的方法来解决这个问题。



现在我唯一的方法知道要打印一个字符串列表就是编写一个迭代列表的函数,打印每个元素(如果列表是[a]则打印,但如果是(a:b)则打印并递归)。但是使用map会很简单...



谢谢!

main 函数的类型应该是 IO t (其中 t 是一个类型变量)。 映射的类型putStrLn ls [IO()] 。这就是你得到这个错误信息的原因。您可以通过在 ghci 中运行以下内容来验证这一点:

  Prelude> ; :类型映射putStrLn ls 
map putStrLn ls :: [IO()]

问题是使用 mapM ,它是 map 的monadic版本。或者,您可以使用 mapM _ ,它与 mapM 相同,但不会从函数中收集返回的值。既然你不关心 putStrLn 的返回值,在这里使用 mapM _ 更合适。 mapM _ 具有以下类型:

  mapM_ :: Monad m => ; (a  - > m b) - > [a]  - > m()

以下是如何使用它:

  ls = [banana,mango,orange] 
main = mapM_ putStrLn ls


I have a list of strings, and tried this:

ls = [ "banana", "mango", "orange" ]

main = do
       map PutStrLn list_of_strings

That didn't work, and I can't understand why.

ghc print-list.hs
print-list.hs:3:0:
    Couldn't match expected type `IO t' against inferred type `[IO ()]'
    In the expression: main
    When checking the type of the function `main'

Any hints? I suppose it has to do with map returning a list and not a value, but I didn't find an easy way to fix this.

Right now the only way I know to print a list of strings is to write a function that will iterate the list, printing each element (print if the list is [a], but print and recurse if it's (a:b)). But it would be much simpler to just use map...

Thanks!

解决方案

The type of the main function should be IO t (where t is a type variable). The type of map putStrLn ls is [IO ()]. This why you are getting this error message. You can verify this yourself by running the following in ghci:

Prelude> :type map putStrLn ls
map putStrLn ls :: [IO ()]

One solution to the problem is using mapM, which is the "monadic" version of map. Or you can use mapM_ which is the same as mapM but does not collect the returned values from the function. Since you don't care about the return value of putStrLn, it's more appropriate to use mapM_ here. mapM_ has the following type:

mapM_ :: Monad m => (a -> m b) -> [a] -> m ()

Here is how to use it:

ls = [ "banana", "mango", "orange" ]
main = mapM_ putStrLn ls

这篇关于Haskell:不能使用“map putStrLn”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆