首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >:sprint var是sprint_即使在被评估之后。

:sprint var是sprint_即使在被评估之后。
EN

Stack Overflow用户
提问于 2022-09-06 01:02:37
回答 1查看 114关注 0票数 0

我读过Why :sprint always prints a "_"?,但似乎遇到了其他的问题。

代码语言:javascript
复制
ghci> sum = foldl (+) 0
ghci> let total = sum [1..1000000]
ghci> :sprint total
total = _ -- This is expected due to lazy eval
ghci> print total
500000500000
ghci> :sprint total
total = _ -- This is NOT expected since total has been evaluated.
ghci> :set -XMonomorphismRestriction -- recommended by one of the other answers.
ghci> :sprint total
total = _
ghci> print total
50000005000000
ghci> :sprint total
total = _
ghci> :sprint sum
sum = _
ghci> ints = [1..5]
ghci> :sprint ints
ints = _
ghci> print ints
[1,2,3,4,5]
ghci> :sprint ints
ints = [1,2,3,4,5] -- Yay!

有用的信息:

代码语言:javascript
复制
ghci> :show
options currently set: none.
base language is: Haskell2010
with the following modifiers:
  -XNoDatatypeContexts
  -XNondecreasingIndentation
GHCi-specific dynamic flag settings:
other dynamic, non-language, flag settings:
  -fexternal-dynamic-refs
  -fignore-optim-changes
  -fignore-hpc-changes
  -fimplicit-import-qualified
warning settings:

代码语言:javascript
复制
$ ghci --version
The Glorious Glasgow Haskell Compilation System, version 9.0.2

那么问题是:为什么,我能做些什么来“解决”这个问题呢?我和https://andrew.gibiansky.com/blog/haskell/haskell-syntax/一起读书

EN

回答 1

Stack Overflow用户

发布于 2022-09-06 01:38:17

启用total扩展后,尝试定义MonomorphismRestriction

代码语言:javascript
复制
ghci> :set -XMonomorphismRestriction 
ghci> sum = foldl (+) 0
ghci> let total = sum [1..1000000]
ghci> :sprint total
total = _
ghci> print total
500000500000
ghci> :sprint total
total = 500000500000

或者您可以给total指定一个特定类型(没有MonomorphismRestriction扩展)。

代码语言:javascript
复制
ghci> sum = foldl (+) 0
ghci> let total = sum [1..1000000] :: Int
ghci> :sprint total
total = _
ghci> print total
500000500000
ghci> :sprint total
total = 500000500000

问题是,在NoMonomorphismRestriction (默认)下,total的类型将是(Num a, Enum a) => a。如果值的类型是多态的,GHCi每次都会对其进行评估,就像这样。因此,:sprintf无法打印计算值。

当您给它一个特定的类型时,:sprintf可以打印计算值。请注意,total的类型将成为与MonomorphismRestriction一起的Integer

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73615785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档