问题描述
我正在尝试为表示多项式的typeclass的show函数构建字符串表示形式.我不断收到类型不匹配的错误,从'Char'到'[Char]',但是据我了解,haskell的"append"函数应该能够将Char连接到字符串/[Char].我不明白问题出在哪里,或者根据收到的错误在哪里寻找解决方案.这是错误的代码:
I am trying to build a string representation for the show function of a typeclass representing a polynomial. I keep getting type errors of a mismatch from 'Char' to '[Char]', but from my understanding haskell's "append" function should be able to concatenate a Char to a string/[Char]. I don't understand where the problem lies, or where to look for a solution based on the errors I receive. here is the faulty code:
newtype Poly a = P [a]
instance (Num a, Show a) => Show (Poly a) where
show p = ["" : form (p !! i) i | i <- [l,(l-1)..0]]
where
l = length p
form e i
| i == 0 = elem
| i == 1 = elem ++ "x + "
| otherwise = elem ++ "x^" ++ (show i) ++ " + "
where elem = show e
我们将不胜感激,在此先感谢您.
any help would be greatly appreciated, thanks in advance.
推荐答案
您写
我不知道你从哪里得到这个主意.这是错的.我猜你已经定义了
I have no idea where you got this idea. It's wrong. I'm guessing you've defined
type Poly a = [a]
我将遵循这个假设.
instance (Num a, Show a) => Show (Poly a) where
这是错误的. Poly
是类型的同义词.您只能声明适当的一类类型的实例(将类型构造函数应用于零个或多个类型变量).您可以改为使用
This is wrong. Poly
is a type synonym. You can only declare instances for proper first-class types (the application of a type constructor to zero or more type variables). You can fix this by using, instead,
newtype Poly a = Poly {getPoly :: [a]}
,但是您需要根据需要包装/解包 Poly
数据构造函数.一旦获得正确的选择,您可能会发现不必要给出 Num
约束.
but then you need to wrap/unwrap the Poly
data constructor as required. Once you've gotten this right, you'll probably see that the Num
constraint you've given is unnecessary.
show p = ["" ++ form (p !! i) i | i <- [(length p)..0]]
有一些问题.最重要的是,它不定义字符串(字符列表),而是定义字符串列表.通常,您可以通过对结果应用 concat
来解决此问题.第二个是" ++ any
只是 anything
,因为将空列表连接到另一个列表不会执行任何操作.第三个问题是您试图倒数,但做错了.该表示法仅能计数.要倒数,您必须显示要倒数:
There are a few problems. The big one is that this does not define a string (list of characters) but rather a list of strings. You can fix this, generally, by applying concat
to the result. The second one is that "" ++ anything
is just anything
, because concatenating the empty list to another list doesn't do anything. The third problem is that you're trying to count down, but you've done it wrong. That notation only counts up. To count down, you have to show that you want to count down:
let lp = length p in [lp, (lp-1) .. 0]
我立即看到的最后一件事(在前两行中重复了其中一些错误):
The last thing I see immediately (some of these mistakes are repeated in the preceding two lines):
| otherwise = e ++ "x^" ++ i ++ " + "
现在, i
是一个 Int
,而 ++
仅适用于列表.这样就行不通了.您需要先使用 show
将 i
转换为字符串. e
的类型为 a
,并且还需要使用 show
转换为字符串.
Now i
is an Int
, and ++
only works for lists. So that will not work. You need to first convert i
to a string using show
. e
is of type a
, and needs to be converted to a string using show
as well.
这篇关于错误无法将预期类型"Char"与实际类型"[Char]"匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!