[英]Filtering odd length strings from a list of strings
I am solving this problem: Using map, filter, and (.) (function composition operator), define a function that examines a list of strings, keeping only those whose length is odd, converts them to upper case letters, and concatenates the results to produce a single string.我正在解决这个问题:使用 map、filter 和 (.)(函数组合运算符),定义一个检查字符串列表的函数,只保留那些长度为奇数的字符串,将它们转换为大写字母,并连接结果生成单个字符串。
I know I can do this with a list comprehension but I have been explicitly instructed to use filter.我知道我可以通过列表理解来做到这一点,但我已经明确指示使用过滤器。 Right now, my code looks like this:
现在,我的代码如下所示:
concatenateAndUpcaseOddLengthStrings :: [String] -> String
concatenateAndUpcaseOddLengthStrings [] = ""
concatenateAndUpcaseOddLengthStrings xs = filter (\x -> length x `mod` 2 == 1) xs
I receive this error: Couldn't match type '[Char]' with 'Char' Expected type: String Actual type: [[Char]]我收到此错误:无法匹配类型 '[Char]' 与 'Char' 预期类型:字符串实际类型:[[Char]]
I am testing the filter function before adding the other components, but I can't get past this error.我正在添加其他组件之前测试过滤器功能,但我无法克服此错误。 Any ideas?
有任何想法吗?
The reason this produces an error is because the filter (…) xs
expression will return a list fo strings, not a single string.产生错误的原因是
filter (…) xs
表达式将返回一个字符串列表,而不是单个字符串。 But your type signature specifies:但是您的类型签名指定:
concatenateAndUpcaseOddLengthStrings :: [String] ->
String
so it expects a String
, not a [String]
.所以它需要一个
String
,而不是一个[String]
。 You can make use of concat :: [[a]] -> [a]
here to concatenate strings:您可以在此处使用
concat :: [[a]] -> [a]
来连接字符串:
concatenateAndUpcaseOddLengthStrings :: [String] -> String
concatenateAndUpcaseOddLengthStrings xs =
concat (filter (odd . length) xs)
or even shorter:甚至更短:
concatenateAndUpcaseOddLengthStrings :: [String] -> String
concatenateAndUpcaseOddLengthStrings =
concat . filter (odd . length)
You however still need to implement the fact that it will convert the characters in the strings that are retained to their uppercase variant.但是,您仍然需要实现这样一个事实,即它会将保留的字符串中的字符转换为它们的大写变体。 I leave that as an exercise.
我把它留作练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.