Search code examples
recursionscheme

Function that splits word


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


Solution

  • I'd love to help you with this. Here is my help:

    • You can differentiate between characters and strings using string? and char?
    • A string is a vector of characters. You can get the length with string-length and access individual characters with string-ref.
    • Strings and vectors are zero indexed like all good languages. Use + and - to calculate the needed index.
    • Use substring to create the new middle string.
    • You use car, cdr, and cons for the actual list parts.
    • Scheme only real looping construct is recursion. named let is often used in cases like this.
    • The logic should be to cons the first element nd recurse until you find a string. There you calculate the index of the last element. You then 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.
    • You need a outer loop if you want this to happen until the list no longer has a string it it. The inner loop needs to know what to do if you end up with the empty list.

    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.