zyt*_*hon 0 haskell functional-programming
作为练习,看看我是否理解map我想要为AZ范围内的每个项目添加一个字符'a' 的功能.
好吧,显然我不会因为我得到这些例外,我不认为是输出:
Prelude> map (++ 'A')['A'..'Z']
<interactive>:46:9:
Couldn't match expected type ‘[a]’ with actual type ‘Char’
Relevant bindings include it :: [[a]] (bound at <interactive>:46:1)
In the second argument of ‘(++)’, namely ‘'A'’
In the first argument of ‘map’, namely ‘(++ 'A')’
In the expression: map (++ 'A') ['A' .. 'Z']
<interactive>:46:14:
Couldn't match expected type ‘[a]’ with actual type ‘Char’
Relevant bindings include it :: [[a]] (bound at <interactive>:46:1)
In the expression: 'A'
In the second argument of ‘map’, namely ‘['A' .. 'Z']’
In the expression: map (++ 'A') ['A' .. 'Z']
<interactive>:46:19:
Couldn't match expected type ‘[a]’ with actual type ‘Char’
Relevant bindings include it :: [[a]] (bound at <interactive>:46:1)
In the expression: 'Z'
In the second argument of ‘map’, namely ‘['A' .. 'Z']’
In the expression: map (++ 'A') ['A' .. 'Z']
Prelude>
Run Code Online (Sandbox Code Playgroud)
我理解++是包含字符串的列表的concat运算符.
我的代码有什么问题?
正如你所说的++是列表的concat运算符.它需要一个列表,并在末尾添加另一个列表,例如[1, 2, 3] ++ [4, 5, 6] == [1,2,3,4,5,6].在您的情况下,问题是您正在尝试将字符添加到字符 - 而不是列表中的列表.
字符串是一个字符列表,所以我们可以这样做:
map (\x -> [x] ++ ['A']) ['A'..'Z']
但是,这有点麻烦和丑陋.如果我们只想在列表的开头添加一个项目,我们可以使用:运算符.通过这种方式,我们可以解决问题.我们可以将字符添加到"A"的开头,而不是在每个字符的末尾添加"A".
例如:
map (\x -> x : "A") ['A'..'Z']
然后,我们可以将ETA减少为:
map (: "A") ['A'..'Z']
正如您可能注意到的那样,我已将"A"替换为"A"."A"是一个字符列表,恰好是一个元素长.现在,我们可以在列表中添加一个字符,即输入,而不必先将两个字符都转换为列表.
我们可以看到,它按预期工作:
Prelude> map (: "A") ['A'..'Z']
["AA","BA","CA","DA","EA","FA","GA","HA","IA","JA","KA","LA","MA","NA","OA","PA","QA","RA","SA","TA","UA","VA","WA","XA","YA","ZA"]
Run Code Online (Sandbox Code Playgroud)