Eric
Eric

Reputation: 11

Tail Recursion in Scheme

I am trying to create two functions. One that encrypts and message and one that decrypts a message. A decrypted message will be a list where the elements are the ascii code representing the letters in the message. An encrypted message is a list with very large, seemingly random numbers in a list.

Here are the two functions that I have written. It is my understanding that each of these functions should return a list of numbers. When I try to decrypt a message I get a "maximum recursion depth exceeded" message.

(set! load-noisily? #t)

(define d 157)
(define e 17)
(define n 2773)

(define msg '(2063 193 758 2227 1860 131 131 169 758 660 1528 1751 2227 660 1684 758 2227 660 169 1020 1239 758 207))

(define printasciis (lambda (l)
    (begin (map (lambda (x) (display (ascii->char x))) l)
        (display "\n"))))

(define (makeasciis S) (map (lambda (x) (char->ascii x)) (string->list S)))

(define (encrypt x)
    (remainder (expt m e) n))

(define (decrypt y)
    (remainder (expt c d) n))

(define (encrypt-list lst)
    (if (null? msg) 'done)
        (cons (encrypt (car msg))
            (encrypt-list (cdr msg))))

(define (decrypt-list lst)
    (if (null? msg) 'done)
        (cons (decrypt (car msg))
            (decrypt-list (cdr msg))))

I believe it's because my recursive functions are not tail recursive. After doing some research on the subject, I seem to have to use an accumulator in order to make them tail recursive. Here lies the problem. I can't seem to figure out how to do this for this example.

I'm very new to scheme and to programming in general so any help would be greatly appreciated.

EDIT: I've included the entire code.

Upvotes: 0

Views: 447

Answers (1)

Óscar López
Óscar López

Reputation: 236004

You have a few minor bugs, but the most serious is that the variables in the procedures don't correspond with the parameter names given. Try this:

(define (printasciis l)
  (for-each (lambda (x) (display (ascii->char x))) l)
  (newline))

(define (makeasciis S) 
  (map (lambda (x) (char->ascii x)) 
       (string->list S)))

(define (encrypt x)
  (remainder (expt x e) n))

(define (decrypt y)
  (remainder (expt y d) n))

(define (encrypt-list msg)
  (if (null? msg)
      'done
      (cons (encrypt (car msg))
            (encrypt-list (cdr msg)))))

(define (decrypt-list msg)
  (if (null? msg)
      'done
      (cons (decrypt (car msg))
            (decrypt-list (cdr msg)))))

Upvotes: 1

Related Questions