I wanted to write a function that splits a word into first, middle, and last characters and creating an individual list for each character. For example:
The word "codes" would be split into:
(list #\c "ode" #\s)
then
(list #\c #\o "d" #\e #\s)
then
(list #\c #\o #\d #\e #\s)
So basically it takes any word and then splits off the first and last character, then repeat the process until every character is converted. Could someone help me with this? Thanks
I'd love to help you with this. Here is my help:
string?
and char?
string-length
and access individual characters with string-ref
.+
and -
to calculate the needed index.substring
to create the new middle string.car
, cdr
, and cons
for the actual list parts.let
is often used in cases like this.cons
the first, cons
the new middle, cons the new last letter, the rest of the list goes as the last cdr. You now have one round.Here is a procedure that iterates until it hits a string, then replaces it with another. Your inner loop would look much like it:
(define (replace-first-string lst replacement)
(let helper ((lst lst))
(cond ((null? lst) '())
((string? (car lst)) (cons replacement (cdr lst)))
(else (cons (car lst) (helper (cdr lst)))))))
(replace-first-string (list #\c "ode" #\s) "here")
; ==> (#\c "here" #\s)
This is not a very efficent procedure to make a list of characters. In Scheme we already have string->list
which produces the same end result.