为什么 :sprint 总是打印“_"? [英] Why :sprint always prints a "_"?

查看:41
本文介绍了为什么 :sprint 总是打印“_"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Prelude> let a = 3
Prelude> :sprint a
a = _
Prelude> let c = "ab"
Prelude> :sprint c
c = _

为什么它总是打印_?我不太明白 :sprint 命令的语义.

Why does it always print a _? I don't quite get the semantics of the :sprint command.

推荐答案

Haskell 是一种惰性语言.在需要"结果之前,它不会评估结果.

Haskell is a lazy language. It doesn't evaluate results until they are "needed".

现在,只需打印一个值就会导致需要"所有这些值.换句话说,如果您在 GHCi 中键入一个表达式,它会尝试打印出结果,这会导致对所有结果进行评估.通常这就是您想要的.

Now, just printing a value causes all of it to be "needed". In other words, if you type an expression in GHCi, it will try to print out the result, which causes it all to be evaluated. Usually that's what you want.

sprint 命令(这是 GHCi 功能,不是 Haskell 语言的一部分)允许您查看此时已评估了多少值.

The sprint command (which is a GHCi feature, not part of the Haskell language) allows you to see how much of a value has been evaluated at this point.

例如:

Prelude> let xs = [1..]
Prelude> :sprint xs
xs = _

所以,我们刚刚声明了 xs,它目前没有被评估.现在让我们打印出第一个元素:

So, we just declared xs, and it's currently unevaluated. Now let's print out the first element:

Prelude> head xs
1
Prelude> :sprint xs
xs = 1 : _

现在 GHCi 已经评估了列表的头部,但仅此而已.

Now GHCi has evaluated the head of the list, but nothing more.

Prelude> take 10 xs
[1,2,3,4,5,6,7,8,9,10]
Prelude> :sprint xs
xs = 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 : _

现在评估前 10 个元素,但还有更多元素.(由于 xs 是一个无限列表,这并不奇怪.)

Now the first 10 elements are evaluated, but more remain. (Since xs is an infinite list, that's not surprising.)

您可以构造其他表达式并一次对它们求值以查看发生了什么.这实际上是 GHCi 调试器的一部分,它可以让您一次一点地单步调试代码.特别是如果您的代码陷入无限循环,您不想print 任何东西,因为这可能会锁定 GHCi.但是你仍然想看看发生了什么......因此sprint,它可以让你看到到目前为止评估的内容.

You can construct other expressions and evaluate them a bit at a time to see what's going on. This is really part of the GHCi debugger, which lets you step through your code one bit at a time. Especially if your code is getting caught in an infinite loop, you don't want to print anything, because that might lock up GHCi. But you still want to see what's going on... hence sprint, which lets you see what's evaluated so far.

这篇关于为什么 :sprint 总是打印“_"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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