在Haksell打印空白列表 [英] Print empty list in Haksell
问题描述
这是一段代码:
import System.Environment
myReverse :: [a] - > ; [a]
myReverse [] = []
main = print(myReverse [])
当我使用GHC进行编译时,出现以下错误:
$ b
<1>编译Main(problem5_myReverse.hs,问题5_myReverse.o)
problem5_myReverse.hs:6:8:
由于使用print'
a0'不明确
引起的(Show a0)没有实例
可能的修正:添加修复这些类型变量的类型签名
注意:有几个潜在的实例:
实例显示双重 - 定义在GHC.Float'
GHC.Float'
实例显示浮动 - 定义在
实例(Integral a,Show a)=> Show(GHC。 Real.Ratio a)
- 定义在GHC.Real'
main'的等式中:main = print(myReverse [])
...加23其他
在表达式中:print(myReverse [])
在
但是,当我将签名从
myReverse :: [a] - > [a]
更改为myReverse :: [Int] - > [Int]
源代码编译时没有任何问题
有人可以告诉我怎么能保持一般签名
[a] - > [a]
但是让它适用于空整数列表?myReverse []
(或) []
),但类型推理器不可能推断列出元素类型,因为它是一个空列表。如果你明确地打电话给myReverse([] :: [Int])
,它将能够为列表找到一个Show
实例以便在打印之前将其转换为字符串。
这是因为列表的
Show 实例是用
Show a =>显示[a]
意味着[a]
只有一个显示
实例ifa
有一个显示
实例。但是在[]
的情况下,没有a
。Here is the piece of code:
import System.Environment myReverse :: [a] -> [a] myReverse [] = [] main = print (myReverse [])
When I compile that with GHC I get the following error:
[1 of 1] Compiling Main ( problem5_myReverse.hs, problem5_myReverse.o ) problem5_myReverse.hs:6:8: No instance for (Show a0) arising from a use of
print' The type variable
a0' is ambiguous Possible fix: add a type signature that fixes these type variable(s) Note: there are several potential instances: instance Show Double -- Defined inGHC.Float' instance Show Float -- Defined in
GHC.Float' instance (Integral a, Show a) => Show (GHC.Real.Ratio a) -- Defined inGHC.Real' ...plus 23 others In the expression: print (myReverse []) In an equation for
main': main = print (myReverse [ ])But when I change the signature from
myReverse::[a]->[a]
tomyReverse::[Int]->[Int]
the source code is compiled without any problemsCan somebody tell how can I keep the general signature
[a] -> [a]
but make it work for empty Integer lists?解决方案From
myReverse []
(or[]
in general), it is not possible to for the type inferencer to infer to list element type because it's an empty list. If you explicitly call e.g.myReverse ([] :: [Int])
, it'll be able to find aShow
instance for the list so that it can convert it to string before printing.This is because the
Show
instance for lists is defined withShow a => Show [a]
meaning that[a]
only has aShow
instance for it ifa
has aShow
instance for it. But there is noa
to start with in the case of[]
.这篇关于在Haksell打印空白列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!