Home > Back-end >  How might I rewrite this function so that it supports a keyword argument while preserving what case-
How might I rewrite this function so that it supports a keyword argument while preserving what case-

Time:08-01

I've read that case-lambda does not directly support keyword arguments. How might I rewrite the code below so that the function greet-weightlifter supports keyword arguments.

(define greet-weightlifter 
  (case-lambda ((nombre nombre-segundo) (string-append "Hola, " nombre " " nombre-segundo "."))
               ((name) (string-append "Hi, " name "."))
               ;((#:pref p) (string-append "Hi, would you do a " p " for me, my gentle athlete?")); this does not work
                             ))

(greet-weightlifter "Vanessa" "Lizárraga")
(greet-weightlifter "Busra")
;(greet-weightlifter #:pref"squat")

The lines that are commented out do not work. I need to rewrite greet-weightlifter in such a way so that the call (greet-weightlifter #:pref"squat") would work. How might I do this?

CodePudding user response:

case-lambda might not support keywords, but pattern matching, in this case in the form of define/match does. Combine that with a default value for the argument and putting any other arguments in a rest list, and:

#lang racket/base
(require racket/match)

(define/match (greet-weightlifter #:pref [move #f] . rst)
  [(#f (list name)) #:when (string? name)
                    (string-append "Hi, " name ".")]
  [(#f (list nombre nombre-segundo)) #:when (and (string? nombre)
                                                 (string? nombre-segundo))
                                     (string-append "Hola, " nombre " " nombre-segundo ".")]
  [(p '()) #:when (string? p)
           (string-append "Hi, would you do a " p " for me, my gentle athlete?")])


(displayln (greet-weightlifter "Vanessa" "Lizárraga"))
(displayln (greet-weightlifter "Busra"))
(displayln (greet-weightlifter #:pref "squat"))

Trying to use other arguments than these three cases, or with values that aren't strings, raises a runtime exception.

  • Related