'Trying to define a Racket function salutation by taking first/last name & greeting while first letter of each word is capital and rest is lowercase

I am currently stuck here and do not know how to include the part where each first letter of each word has to be uppercase and the rest has to be lowercase. Other than that, printing the greeting itself is pretty straightforward. I am new to Racket and functional programming in general.

; Language: Racket
;
; TODO: Define below the function salutation, which takes a first name, a last name,
; and a greeting word, and then produces a resulting combined welcome.
;
; Be careful to correct for capitalization in all inputs: no matter how
; they are supplied, all should be output with the first letter upper-case
; and the rest lower-case. For example...
;
; (salutation "hello" "jane" "doe") should result in "Hello Jane Doe"
; (salutation "WELCOME" "bOb" "SMiTh") should result in "Welcome Bob Smith"

(define (salutation greeting first-name last-name)
  (string-append
   greeting
   " "
   first-name
   " "
   last-name))

(salutation "hello" "jane" "doe")


Solution 1:[1]

The most straightforward way will be string-titlecase. You can also use map and string-join (which is provided by racket/string library) to avoid writing that three times.

See also Racket Docs for Strings for some other useful functions.

#lang racket

(require racket/string)

(define (salutation greeting first-name last-name)
  (string-join (map string-titlecase (list greeting first-name last-name))
               " "))

(salutation "hello" "jane" "doe")
(salutation "WELCOME" "bOb" "SMiTh")

EDIT: BSL solution:

(define (my-titlecase str)
  (if (zero? (string-length str)) ""
      (string-append (string-upcase (string-ith str 0))
                     (string-downcase (substring str 1)))))

(define (salutation greeting first-name last-name)
  (string-append
   (my-titlecase greeting)
   " "
   (my-titlecase first-name)
   " "
   (my-titlecase last-name)))

(salutation "hello" "jane" "doe")
(salutation "WELCOME" "bOb" "SMiTh")

Solution 2:[2]

Or use format:

(define (saluation greeting first-name last-name)
  (format "~a, ~a ~a!" greeting first-name last-name))

~a is a placeholder for the corresponding arguments in the format expression.

Simple string concatenation, you can do even with:

(~a "a" "b" "c") ;; => "abc"

So you could also do:

(define (saluation greeting first-name last-name)
  (~a greeting ", " first-name " " last-name "!"))

format comes from Common Lisp and is very powerful.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2