In JavaScript you can join an array of strings, e.g.:
fruits = ["orange", "apple", "banana"];
joined = fruits.join(", ");
console.log(joined)
// "orange, apple, banana"
How do you do this in ReasonML?
In JavaScript you can join an array of strings, e.g.:
fruits = ["orange", "apple", "banana"];
joined = fruits.join(", ");
console.log(joined)
// "orange, apple, banana"
How do you do this in ReasonML?
You can use Js.Array.joinWith
:
let fruits = [|"orange", "apple", "banana"|];
let joined = Js.Array.joinWith(", ", fruits);
Js.log(joined);
// "orange, apple, banana"
Js.Array.join
is discouraged, as it compiles to JS array.join()
, which uses a comma as a separator. –
Devoted Js.Array.join
from my answer. –
Madigan Converting an array to a string of joined values sounds like a job for Array.fold_left, however running
Array.fold_left((a, b) => a ++ "," ++ b, "", fruits);
produces ",orange,apple,banana".
Ideally the starting value for the fold (second argument) should the the first element in the array and the array actually used would be the rest, this avoids the initial comma. Unfortunately, this isn't easily doable with arrays, but is with lists:
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"*/
Here's how to implement your own join
function in ReasonML:
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)
};
};
With this, Js.log(join("$", ["a", "b", "c"]))
gives you "a$b$c"
, much like JavaScript would.
© 2022 - 2024 — McMap. All rights reserved.