简体   繁体   English

Haskell:无法将类型'Char'与'[Char]'匹配

[英]Haskell: Couldn't match type ‘Char’ with ‘[Char]’

I'm a Haskell beginner and I'm wrestling using functions to modify a list and then return it back to a string. 我是Haskell的初学者,我正在努力使用函数来修改列表,然后将其返回到字符串。 I'm running into this error however. 我遇到了这个错误。 Any advice? 有什么建议吗?

Couldn't match type 'Char' with '[Char]' 无法将类型'Char'与'[Char]'相匹配

Expected type: String 预期类型:字符串

Actual type: Char 实际类型:字符

createIndex:: String -> String
createIndex str = unLine (removeT (splitLines str))

splitLines:: String -> [String]
splitLines splitStr = lines splitStr

removeT:: [String] -> [String]
removeT strT = filter (=='t') strT

unLine:: [String] -> String
unLine unLinedStr = unlines unLinedStr

The problem is in your definition of removeT . 问题出在您的removeT定义中。 The type of removeT is [String] -> [String] , meaning it works on a list of lists of characters. removeT的类型是[String] -> [String] ,这意味着它适用于字符列表。 Then, in your filter , you compare each list of characters (ie, each String in the list) to a Char ( 't' ). 然后,在filter ,将每个字符列表(即列表中的每个String )与一个Char't' )进行比较。 This is not allowed (you cannot check values with different types for equality). 不允许这样做(您不能检查其他类型的值是否相等)。

How to change your code really depends on what you intend to do. 如何更改代码实际上取决于您打算做什么。 It's not entirely clear if you want to remove lines containing t's, if you want to keep lines containing t's, if you want to remove t's, or if you want to keep t's. 是否要删除包含t的行,是否要保留包含t的行,是否要删除t或是否要保留t尚不完全清楚。 Depending on what you want to achieve, your code will have to be modified accordingly. 根据您要实现的目标,必须对代码进行相应的修改。

Some pointers: 一些指针:

  • If you change the type of removeT to String -> String you can look at one line at a time. 如果将removeT的类型更改为removeT String -> String ,则可以一次查看一行。 You would then have to replace removeT in the definition of createIndex by map removeT (because you're applying the function to each line)). 然后,你将不得不更换removeT在定义createIndex通过map removeT (因为你申请的功能,每行))。 In this case, the filter would deal with Char values so comparing with a 't' is allowed. 在这种情况下,过滤器将处理Char值,因此允许与“ t”进行比较。

  • If you want to do something with lines containing t's, (== 't') is not the way to go, you will want to use ('t' `elem`) (meaning "'t' is an element of"). 如果您想对包含t的行进行处理,则(== 't')并非('t' `elem`) ,您将需要使用('t' `elem`) (意思是“'t'是”的元素) 。

  • filter keeps elements matching the predicate. filter器使元素与谓词匹配。 So if you want to remove t's from a string for example, you use filter (/= 't') . 因此,例如,如果要从字符串中删除t,请使用filter (/= 't')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM