ghci是否适用于特殊情况? [英] ghci special case for Applicative?

查看:111
本文介绍了ghci是否适用于特殊情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ghci中:

λ> :t (pure 1)
(pure 1) :: (Applicative f, Num a) => f a
λ> show (pure 1)

<interactive>:1:1:
    No instance for (Show (f0 a0))
      arising from a use of `show'
    Possible fix: add an instance declaration for (Show (f0 a0))
    In the expression: show (pure 1)
    In an equation for `it': it = show (pure 1)
λ> pure 1
1

这是否意味着ghci执行Applicative并显示结果,就像IO一样?

Does this mean that ghci execute Applicative and displays the result, just like IO?

请注意,pure ()pure (+1)不会打印任何内容.

Note that pure () and pure (+1) don't print anything.

推荐答案

如果使用return而不是pure,则会得到相同的行为.要找出要执行的操作,ghci必须为给定的表达式选择一种类型. ghci的默认规则是在没有其他约束的情况下,它为ApplicativeMonad实例选择IO.因此,它将pure 1解释为类型IO Integer的表达式.如果1.a具有Show实例,而2.a不是(),则在提示符下输入的类型为IO a的表达式将被执行并打印其结果.因此,在提示符下输入pure 1会导致

You get the same behaviour if you use return instead of pure. To find out what to do, ghci must choose a type for the given expression. ghci's defaulting rules are such that absent other constraints, it chooses IO for an Applicative or Monad instance. Thus it interprets pure 1 as an expression of type IO Integer. Expressions of type IO a entered at the prompt are executed and their results are printed, if 1. a has a Show instance and 2. a is not (). Thus entering pure 1 at the prompt results in

v <- return (1 :: Integer)
print v
return v

被执行(魔术变量it绑定到返回的v).对于pure (),特殊情况适用,因为认为()不感兴趣,因此仅执行return ()并将it绑定到(),对于pure (+1),将返回一个函数,没有Show实例范围内的功能,因此不会打印任何内容.但是,

being executed (and the magic variable it bound to the returned v). For pure (), the special case applies since () is considered uninteresting, thus only return () is executed and it bound to (), for pure (+1), a function is returned, there's no Show instance for functions in scope, so nothing is printed. However,

Prelude Control.Applicative> :m +Text.Show.Functions
Prelude Control.Applicative Text.Show.Functions> pure (+1)
<function>
it :: Integer -> Integer
Prelude Control.Applicative Text.Show.Functions> it 3
4
it :: Integer

具有作用域中的函数的Show实例,它会被打印出来(不是提供信息的内容),然后可以使用该函数(后者当然与作用域中的Show实例无关).

with a Show instance for functions in scope, it gets printed (not that it's informative), and the function can then be used (the latter is independent of a Show instance being in scope, of course).

这篇关于ghci是否适用于特殊情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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