In: Computer Science
*****************PLEASE PROVIDE THE CODE IN RACKET PROGRAMMING LANGUAGE ONLY AND MAKE SURE CODE RUNS ON THE WESCHEME IDE*************
Write a tail-recursive Racket function "kept-short-rec" that takes an integer and a list of strings as parameters and evaluates to an integer. The resulting integer should be the number of strings on the original list whose string length is less than the integer parameter. For example, (kept-short-rec 3 '("abc" "ab" "a")) should evaluate to 2 because there are only 2 strings shorter than 3.
Your solution must be tail-recursive. Recall that a function is tail-recursive if it is recursive and every recursive call has no work to be done after the call completes. Note: (string-length s) evaluates to the length of string s.
(define (kept-short-rec-helper acc n xs)
(if (empty? xs)
???
(if (< (string-length (first xs)) n)
???
???))
(define (kept-short-rec n xs)
(kept-short-rec-helper ??? n xs))
Hello, here's the documented code to solve the assignment:
(define (kept-short-rec-helper acc n xs)
(if (empty? xs)
acc ; in the base case, where the list xs is empty, we return the accumulator value, acc
(if (< (string-length (first xs)) n)
(kept-short-rec-helper (+ acc 1) n (rest xs)) ; the current string is acceptable
(kept-short-rec-helper acc n (rest xs))))) ; the current string is not acceptable
(define (kept-short-rec n xs)
(kept-short-rec-helper 0 n xs))
(writeln (kept-short-rec 3 '("abc" "ab" "a")))
Here is a snapshot of a demo run:
Hope this helps! :)