Skip to content

Instantly share code, notes, and snippets.

@manveru
Created March 24, 2024 22:49
Show Gist options
  • Save manveru/355c9b995a72fe906dc7de568b33c737 to your computer and use it in GitHub Desktop.
Save manveru/355c9b995a72fe906dc7de568b33c737 to your computer and use it in GitHub Desktop.
traditional string formatting in gleam
import gleam/dynamic
import gleam/int
import gleam/list
import gleam/string
import gleam/bit_array
import gleam/io
pub fn main() {
let assert Ok(s) = fmt("formatted: %d %b", #(123, <<123>>))
io.println(s)
}
fn fmt(format, args) {
fmt_rec(string.to_graphemes(format), dynamic.from(args), 0, [])
}
fn fmt_rec(format, args, index, output) {
case format {
[] ->
list.reverse(output)
|> string.join("")
|> Ok()
["%", "%", ..rest] -> fmt_rec(rest, args, index, ["%", ..output])
["%", "s", ..rest] ->
case dynamic.element(index, dynamic.string)(args) {
Ok(element) -> fmt_rec(rest, args, index + 1, [element, ..output])
Error(_err) -> Error("not a string")
}
["%", "d", ..rest] ->
case dynamic.element(index, dynamic.int)(args) {
Ok(element) ->
fmt_rec(rest, args, index + 1, [int.to_string(element), ..output])
Error(_err) -> Error("not an integer")
}
["%", "b", ..rest] ->
case dynamic.element(index, dynamic.bit_array)(args) {
Ok(element) ->
fmt_rec(rest, args, index + 1, [bit_array.inspect(element), ..output])
Error(_err) -> Error("not a bit_array")
}
[c, ..rest] -> fmt_rec(rest, args, index, [c, ..output])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment