[英]Making a list of strings lowercase in Haskell
I have a list of strings ["Hi", "hELLO", "nO"]
我有一个字符串列表
["Hi", "hELLO", "nO"]
and I want to convert everything to lowercase.我想将所有内容都转换为小写。 I wrote a function for this:
我为此写了一个函数:
import Data.Char(toLower)
makeSmall xs = map toLower xs
It compiles, but when I do makeSmall ["Hi", "hELLO", "nO"]
it gives me this error它可以编译,但是当我执行
makeSmall ["Hi", "hELLO", "nO"]
它给了我这个错误
<interactive>:2:12: error:
• Couldn't match expected type ‘Char’ with actual type ‘[Char]’
• In the expression: "Hi"
In the first argument of ‘makeSmall’, namely
‘["Hi", "hELLO", "nO"]’
In the expression: makeSmall ["Hi", "hELLO", "nO"]
<interactive>:2:17: error:
• Couldn't match expected type ‘Char’ with actual type ‘[Char]’
• In the expression: "hELLO"
In the first argument of ‘makeSmall’, namely
‘["Hi", "hELLO", "nO"]’
In the expression: makeSmall ["Hi", "hELLO", "nO"]
<interactive>:2:25: error:
• Couldn't match expected type ‘Char’ with actual type ‘[Char]’
• In the expression: "nO"
In the first argument of ‘makeSmall’, namely
‘["Hi", "hELLO", "nO"]’
In the expression: makeSmall ["Hi", "hELLO", "nO"]
I'm trying to understand how I can make my function work for a list of strings, instead of just a string我试图了解如何使我的函数适用于字符串列表,而不仅仅是字符串
toLower :: Char -> Char
maps a Char
to a Char
, this means that map toLower
will take a single String
, and it will return a String
. toLower :: Char -> Char
映射一个Char
一个Char
,这意味着map toLower
将采取单一的String
,它会返回一个String
。
If you want to handle a list of String
s, you should use a second map
:如果要处理
String
列表,则应使用第二个map
:
makeSmall :: [String] -> [String]
makeSmall xs = map (map toLower) xs
or shorter:或更短:
makeSmall :: [String] -> [String]
makeSmall = map (map toLower)
We thus make a mapper that uses map toLower
as map function.因此,我们制作了一个使用
map toLower
作为 map 函数的映射器。 This function will thus work on a single String
.因此,此函数将在单个
String
上工作。 Since we make thus a mapper for this, we work on a list of String
s.由于我们为此制作了一个映射器,因此我们处理
String
的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.