如何连接两个字符串.例如,我有两个列表
["me","you","he"]和 ["she","they","it"].我想形成一个新的列表,其中每个相应的字符串组合到gatheer,比如
["meshe","youthey","heit"].现在我的问题是:如何组合两个字符串
combine = zipWith (++)
Run Code Online (Sandbox Code Playgroud)
zipWith采用两个列表,并将给定的功能应用于两个列表的第一项,然后应用第二项等.如果一个列表比另一个列表长,则将跳过其额外项目.
该++函数采用两个列表并将它们连接在一起.字符串只是一个字符列表.
"hello " ++ "world" == "hello world"
用法:
?> combine ["me","you","he"] ["she","they","it"]
["meshe","youthey","heit"]
?> combine [] []
[]
?> combine ["me", "you"] ["she"]
["meshe"]
?>
Run Code Online (Sandbox Code Playgroud)
虽然++操作员非常基本,所以在进入stackoverflow之前,你可能会更好地继续阅读你正在使用的任何学习材料,因为你会有很多问题我希望你的书中会有答案.
如果你不想使用zipWith,你可以非常简单地用递归来编写它,如下所示:
combine [] _ = []
combine _ [] = []
combine (x:xs) (y:ys) = (x ++ y) : combine xs ys
Run Code Online (Sandbox Code Playgroud)
用法与以前相同.
| 归档时间: |
|
| 查看次数: |
2136 次 |
| 最近记录: |