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.

Open in playground
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()
}

An exercism exercise from the Gleam track, solved in Bea: beacode/src/e14_highschool_sweetheart.bea