Let's implode! →
In one of the previous posts we looked at a recursive function explode
to explode a string into a list of characters. Now, we shall try to implode a list of characters back into a string. We’ll call this function implode
that takes a list lst
as input.
We need an accumulator in order to collect the characters from the input list to prepare our output, so let’s create one acc
whose length would be equal to the length of the input list lst
(of characters).
- Base case - if the input list
lst
is an empty one, just return the accumulator. - If the list is not empty, we pick the head element and push it into the accumulator. We start with index
'0'
of the (mutable) String and recursively call the function on the remaining part of the list, incrementing the index for each call.
Note: The latest version of OCaml, my preferred programming language, has a mutable data-type Bytes
while it made the String
data-type immutable.
Food for thought - how would be implement implode
using the immutable String type, in a purely functional fashion?