fmap打印值不打印任何东西 [英] fmap print value doesn't print anything

查看:134
本文介绍了fmap打印值不打印任何东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下内容不会打印任何内容:

 λ> fmap print(pure 2)

类似这样的工作:

 λ> fmap id(pure 2)
2


解决方案

按照以下类型:

  fmap print(pure 2):: Applicative f => f(IO())
fmap id(纯2)::(Num b,Applicative f)=> fb

让我们用<$ c替换 f
$ b $ pre $ f $ print(pure 2):: IO(IO())$ c $> $ c $> $ / code>:

- #1
fmap id(pure 2)::(Num b)=> IO b - #2

现在您可以清楚地看到#2是一个带有数字结果的动作,而#1是另一个行动的结果。



另外,GHCi有以下关于互动评估的规则


2.4。在提示符下进行交互式评估



在提示符下键入表达式时,GHCi会立即评估并显示结果:

< H3> 2.4.1。提示时的I / O操作

GHCi不仅仅是在提示时进行简单表达式评估。如果您为 a 键入 IO a 类型的某些内容,则GHCi将其作为IO计算执行。



此外,GHCi会在下列情况下打印I / O动作的结果:


  • 结果类型是 Show 的一个实例。


  • 由于结果类型不是()。

IO a 不是 Show 的实例,它不会打印IO动作的结果。


Why does the following doesn't print anything:

λ> fmap print (pure 2)

Whereas something like this works:

λ> fmap id (pure 2)
2

解决方案

Follow the types:

fmap print (pure 2) :: Applicative f => f (IO ())
fmap id (pure 2)    :: (Num b, Applicative f) => f b

Lets replace f with IO:

fmap print (pure 2) :: IO (IO ())      -- #1
fmap id (pure 2)    :: (Num b) => IO b -- #2

Now you can clearly see that #2 is an action with a numeric result, whereas #1 is an action with another action as a result.

Also, GHCi has the following rules about interactive evaluation:

2.4. Interactive evaluation at the prompt

When you type an expression at the prompt, GHCi immediately evaluates and prints the result:

2.4.1. I/O actions at the prompt

GHCi does more than simple expression evaluation at the prompt. If you type something of type IO a for some a, then GHCi executes it as an IO-computation.

Furthermore, GHCi will print the result of the I/O action if (and only if):

  • The result type is an instance of Show.

  • The result type is not ().

Since IO a is not an instance of Show, it won't print the result of the IO action.

这篇关于fmap打印值不打印任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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