0

Language BSL - DrRacket (racket variant)

Problem: I need to understand what the function below does exactly. Specifically the substring bit, I don't understand how it determines whether a string has an "?" at the end in choosing whether to append "?" to the consumed string.

(define (ensure-question str)
  (if (string=? (substring str (- (string-length str) 1)) "?")
      str
      (string-append str "?")))
Flux
  • 9,805
  • 5
  • 46
  • 92

1 Answers1

2

(substring s position) function returns substring of string s from certain position. For example : (substring "Apple" 1) returns "pple" since we are taking subscript from the first character.

(substring "Apple" ( - (string-length "Apple") 1))

will return "e".

We are taking subscript including only the last character (- (string-length str) 1)) and checking whether it equals to "?" by using function string=?.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
ig-melnyk
  • 2,769
  • 2
  • 25
  • 35