在Haksell打印空白列表 [英] Print empty list in Haksell

查看:135
本文介绍了在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'
引起的(Show a0)没有实例
a0'不明确
可能的修正:添加修复这些类型变量的类型签名
注意:有几个潜在的实例:
实例显示双重 - 定义在 GHC.Float'
实例显示浮动 - 定义在
GHC.Float'
实例(Integral a,Show a)=> Show(GHC。 Real.Ratio a)
- 定义在 GHC.Real'
...加23其他
在表达式中:print(myReverse [])
main'的等式中:main = print(myReverse [])




但是,当我将签名从 myReverse :: [a] - > [a] 更改为 myReverse :: [Int] - > [Int] 源代码编译时没有任何问题



有人可以告诉我怎么能保持一般签名 [a] - > [a] 但是让它适用于空整数列表? myReverse [] (或 [] ),但类型推理器不可能推断列出元素类型,因为它是一个空列表。如果你明确地打电话给 myReverse([] :: [Int]),它将能够为列表找到一个 Show 实例以便在打印之前将其转换为字符串。

这是因为列表的 Show 实例是用 Show a =>显示[a] 意味着 [a] 只有一个显示实例if a 有一个显示实例。但是在 [] 的情况下,没有 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 variablea0' is ambiguous Possible fix: add a type signature that fixes these type variable(s) Note: there are several potential instances: instance Show Double -- Defined in GHC.Float' instance Show Float -- Defined inGHC.Float' instance (Integral a, Show a) => Show (GHC.Real.Ratio a) -- Defined in GHC.Real' ...plus 23 others In the expression: print (myReverse []) In an equation formain': main = print (myReverse [ ])

But when I change the signature from myReverse::[a]->[a] to myReverse::[Int]->[Int] the source code is compiled without any problems

Can 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 a Show instance for the list so that it can convert it to string before printing.

This is because the Show instance for lists is defined with Show a => Show [a] meaning that [a] only has a Show instance for it if a has a Show instance for it. But there is no a to start with in the case of [].

这篇关于在Haksell打印空白列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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