:sprint var正在打印——即使在评估之后也是如此



我读了为什么:sprint总是打印一个&quot_"?但我似乎遇到了别的事情。

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!

有用信息:

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:

$ ghci --version
The Glorious Glasgow Haskell Compilation System, version 9.0.2

因此,问题是:为什么以及我能做些什么来";"修复";这我和https://andrew.gibiansky.com/blog/haskell/haskell-syntax/

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

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扩展名(。

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的类型将变为具有MonomorphismRestrictionInteger

最新更新