Type-safe (string) formatting for Gleam.
Heavily inspired by "Type-safe functional formatted IO" by Oleg Kiselyov.
The following code would print out Movie: Inside Out; Rating: 5; Price: $24.99
:
import fmt
import gleam/io
// This will print out "Movie: Inside Out; Rating: 5; Price: $24.99"
pub fn main() {
fmt.lit("Movie: ")
|> fmt.cat(fmt.string())
|> fmt.cat(fmt.lit("; Rating: "))
|> fmt.cat(fmt.int())
|> fmt.cat(fmt.lit("; Price: $"))
|> fmt.cat(fmt.float())
|> fmt.sprintf3("Inside Out", 5, 24.99)
|> io.println
}
In this example,
lit
is used to specify literal string values.string
is used to specify aString
placeholder.int
is used to specify anInt
placeholder.float
is used to specify aFloat
placeholder.cat
is used to concatenate the formatting specifications.sprintf3
is used to generate the string from the given specification.
For more details and examples, see the documentation and the tests.
It is type-safe: the compiler will ensure that you have set everything up correctly, both in terms of the number of expected arguments and their types.
Check out this example:
pub fn will_fail() {
fmt.lit("Name: ")
|> fmt.cat(fmt.string())
|> fmt.cat(fmt.lit("; Age: "))
|> fmt.cat(fmt.int())
|> fmt.sprintf2("Juan", "Carlos")
}
If you were to check this with gleam check
, you would get an error something like this:
error: Type mismatch
┌─ ./fmt/test/fmt_test.gleam:82:27
│
82 │ |> fmt.sprintf2("Juan", "Carlos")
│ ^^^^^^^^
Expected type:
Int
Found type:
String
There are a couple other Gleam formatting libraries that I am aware of. You may be interested in them as well!
Note: The following example code blocks are taken from the respective project READMEs.
Glormat provides a readable style of format strings, and a pipeline-based API.
import gleam/io
import glormat.{assert_ok, replace, then, then_debug}
pub fn main() {
"hello {object}, the {operation} is {result}"
|> replace("object", with: "world")
|> then("operation", with: "sum")
|> then_debug("result", with: 1 + 2)
|> assert_ok
|> io.println // hello world, the sum is 3
}
Sprinkle uses readable format strings and uses string tuples to specify replacements.
import sprinkle.{format}
pub fn main() {
let output = format("My name is {name} and I like to do {activity}!", [
#("name", "Lily"),
#("activity", "programming")
])
}
Copyright (c) 2024 Ryan M. Moore
Licensed under the Apache License, Version 2.0 or the MIT license, at your option. This program may not be copied, modified, or distributed except according to those terms.