Join array of strings?
Asked Answered
B

3

7

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?

Beebe answered 20/4, 2018 at 14:32 Comment(4)
What's wrong with the question?Beebe
@glennsl This question was ask and answered for almost every language on SO. It's a shame no one is willing to answer it for ReasonML. I did some research and no it's not obvious for a new-comer that any of your solutions are the way to go. What a welcoming community.Beebe
@glennsl the reason that stackoverflow is useful to developers is that it has answers to almost any question. For many languages stackoverflow becomes much easier than the docs to find solution. Just my opinion.Miche
The answer is probably different for native or bucklescript, it should be specified in the question. Can you give some feedback to the answers you got?Devoted
M
9

You can use Js.Array.joinWith:

let fruits = [|"orange", "apple", "banana"|];
let joined = Js.Array.joinWith(", ", fruits);
Js.log(joined);
// "orange, apple, banana"
Madigan answered 26/4, 2018 at 11:9 Comment(2)
The use of Js.Array.join is discouraged, as it compiles to JS array.join(), which uses a comma as a separator.Devoted
Correct, I removed the reference to Js.Array.join from my answer.Madigan
M
5

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"*/

Reasonml docs on lists

Marnie answered 23/5, 2018 at 14:12 Comment(0)
S
3

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.

Stanhope answered 3/7, 2018 at 6:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.