Skip to content

Instantly share code, notes, and snippets.

@Chubek
Created May 27, 2024 22:16
Show Gist options
  • Save Chubek/524bcc10abc593710f7de9ccca8377e4 to your computer and use it in GitHub Desktop.
Save Chubek/524bcc10abc593710f7de9ccca8377e4 to your computer and use it in GitHub Desktop.
SML's "implode" and "explode" in OCaml

In Standard ML, we have two built-in functions called 'explode' and 'implode':

fun explode: string -> char list
fun implode: char list -> string

So, you get it, 'explode' makes a list of characters from a string and 'implode' does the inverse.

However, OCaml does not have these functions. Regardless; you may derive them like so:

let explode s = List.init (String.length s) (String.get s)
let implode l = String.init (List.length l) (List.nth l)

Enjoy.

@Chubek
Copy link
Author

Chubek commented Jun 11, 2024

Using List.nth will give you bad time complexity since list access is linear not random. Prefer this:

let explode s = List.of_seq (String.to_seq s)
let implode l = String.of_seq (List.to_seq l)

also OCaml offers some char-by-char iteration functions on String directly so that you don't have to convert to an intermediate format:

    val map : (char -> char) -> string -> string
    val mapi : (int -> char -> char) -> string -> string
    val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc
    val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc
    val for_all : (char -> bool) -> string -> bool
    val exists : (char -> bool) -> string -> bool
    val iter : (char -> unit) -> string -> unit
    val iteri : (int -> char -> unit) -> string -> unit

Thanks man.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment