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?

Rotareti
  • 49,483
  • 23
  • 112
  • 108
  • What's wrong with the question? – Rotareti Apr 20 '18 at 15:02
  • 5
    @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. – Rotareti Apr 21 '18 at 10:43
  • 3
    @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. – JasoonS Apr 28 '18 at 13:30
  • 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? – tokland Jul 10 '18 at 21:46

3 Answers3

9

You can use Js.Array.joinWith:

let fruits = [|"orange", "apple", "banana"|];
let joined = Js.Array.joinWith(", ", fruits);
Js.log(joined);
// "orange, apple, banana"
noziar
  • 1,017
  • 7
  • 11
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

shtanton
  • 86
  • 1
  • 4
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.

Bertrand
  • 1,718
  • 2
  • 13
  • 24