在JavaScript中,您可以加入一个字符串数组,例如:
fruits = ["orange", "apple", "banana"];
joined = fruits.join(", ");
console.log(joined)
// "orange, apple, banana"
你如何在ReasonML中做到这一点?
答案 0 :(得分:6)
您可以使用Js.Array.joinWith
:
let fruits = [|"orange", "apple", "banana"|];
let joined = Js.Array.joinWith(", ", fruits);
Js.log(joined);
// "orange, apple, banana"
答案 1 :(得分:3)
将数组转换为连接值的字符串听起来像是Array.fold_left的作业,无论如何运行
Array.fold_left((a, b) => a ++ "," ++ b, "", fruits);
生产“,橙子,苹果,香蕉”。
理想情况下,fold(第二个参数)的起始值应该是数组中的第一个元素,而实际使用的数组将是其余元素,这样可以避免使用初始逗号。不幸的是,这对于数组来说并不容易,但是使用列表:
let fruitList = Array.to_list(fruits);
let joined = List.fold_left((a, b) => a ++ "," ++ b, List.hd(fruitList), List.tl(fruitList));
/*joined = "orange,apple,banana"*/
答案 2 :(得分:2)
以下是在ReasonML中实现自己的join
函数的方法:
let rec join = (char: string, list: list(string)): string => {
switch(list) {
| [] => raise(Failure("Passed an empty list"))
| [tail] => tail
| [head, ...tail] => head ++ char ++ join(char, tail)
};
};
有了这个,Js.log(join("$", ["a", "b", "c"]))
就给了"a$b$c"
,就像JavaScript一样。