Chapter 4: Functions as values
High school sweetheart
- string functions
- multi-line strings
Pipelines can span several lines; a line that starts with
|> continues the expression above it.
Ok(first) = … |> string.first() asserts that the name
isn't empty. Strings can span lines, and interpolation works inside them,
which is how the initials land in the middle of the heart.
import gleam/string
import gleam/list
import gleam/io
def cleanup(name: String) -> String {
name
|> string.trim()
}
def first_letter(name: String) -> String {
Ok(first) =
name
|> cleanup()
|> string.first()
first
}
def initial(name: String) -> String {
name
|> first_letter
|> string.uppercase()
<> "."
}
def initials(fullname: String) -> String {
fullname
|> string.split(" ")
|> list.map(initial)
|> string.join(" ")
}
def pair(fullname1: String, fullname2: String) -> String {
"
****** ******
** ** ** **
** ** ** **
** * **
** **
** #{initials(fullname1)} + #{initials(fullname2)} **
** **
** **
** **
** **
** **
** **
***
*
"
}
pub def main() {
pair("James Pazo", "Rachel Kiador")
|> io.println()
}import gleam/io
import gleam/list
import gleam/string
fn cleanup(name: String) -> String {
name |> string.trim()
}
fn first_letter(name: String) -> String {
let assert Ok(first) = name |> cleanup() |> string.first()
first
}
fn initial(name: String) -> String {
name |> first_letter |> string.uppercase() <> "."
}
fn initials(fullname: String) -> String {
fullname |> string.split(" ") |> list.map(initial) |> string.join(" ")
}
fn pair(fullname1: String, fullname2: String) -> String {
"
****** ******
** ** ** **
** ** ** **
** * **
** **
** " <> initials(fullname1) <> " + " <> initials(fullname2) <> " **
** **
** **
** **
** **
** **
** **
***
*
"
}
pub fn main() {
pair("James Pazo", "Rachel Kiador") |> io.println()
}
****** ******
** ** ** **
** ** ** **
** * **
** **
** J. P. + R. K. **
** **
** **
** **
** **
** **
** **
***
*An exercism exercise from the Gleam track, solved in Bea: beacode/src/e14_highschool_sweetheart.bea