简体   繁体   English

Haskell,打印出fmap结果

[英]Haskell, print out fmap result

I would like to print result of fmap like this 我想像这样打印fmap的结果

 putStrLn <- fmap (replicate 3) [1,2,3,4]

But I got putStrLn parse error. 但是我遇到了putStrLn分析错误。 Please help. 请帮忙。

Thank you. 谢谢。

The correct syntax here is: 正确的语法是:

putStrLn $ show $ fmap (replicate 3) [1,2,3,4]

or, even shorter: 或者,甚至更短:

print $ fmap (replicate 3) [1,2,3,4]

Totally not the answer the asker is looking for, but humorously his syntax misunderstanding is still valid Haskell code: 完全不是问问者所寻求的答案,但是幽默地讲,他对语法的误解仍然是有效的Haskell代码:

do putStrLn <- fmap (replicate 3) [1,2,3,4]
   return putStrLn

The above uses the list monad and the value putStrLn is just a variable (not the IO action one might expect). 上面使用列表monad,值putStrLn只是一个变量(不是人们可能期望的IO操作)。 It might make more sense to people if expressed as a list comprehension instead of using the list monad: 如果将其表示为列表理解而不是使用列表单子,那么对人们来说可能更有意义:

> [ putStrLn | putStrLn <- map (replicate 3) [1,2,3,4]]
[[1,1,1],[2,2,2],[3,3,3],[4,4,4]]

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

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