In: Computer Science
*****************PLEASE GIVE THE CODE IN RACKET PROGRAMMING ONLY AND MAKE SURE THE CODE RUNS ON WESCHEME IDE***************
Write a recursive Racket function "keep-short-rec" that takes an integer and a list of strings as parameters and evaluates to a list of strings. The resulting list should be all of the strings from the original list, maintaining their relative order, whose string length is less than the integer parameter. For example, (keep-short-rec 3 '("abc" "ab" "a")) should evaluate to '("ab" "a") because these are the only strings shorter than 3. Your solution must be recursive. Note: (string-length s) evaluates to the length of string s
Code:
#lang racket
(define (keep-short-rec n lst)
; if the list is null, return null
(cond ((null? lst) null)
; if the length of the first string in the list is less
than n,
; then return a new list which is made up of first string in the
list and return value of (keep-short-rec n (cdr
lst))
((< (string-length (car lst)) n) (cons (car lst) (keep-short-rec
n (cdr lst))))
; if the length of the first string in the list is greater
than or equal to n,
; return (keep-short-rec n (cdr lst))
(else (keep-short-rec n (cdr lst)))
)
)
; testing the keep-short-rec function
(keep-short-rec 3 '("abc" "ab" "a"))
(keep-short-rec 4 '("abcde" "ab" "a" "abcdefghij" "abcdef"
"abc"))
Code Screenshot and Output: