Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In beginner scheme how do I represent a variable as a string?

Tags:

scheme

racket

My question is how do i code for

(triangle 5) produces (list "*****" "****" "***" "**" "*")

Note: (5 astericks 4, then 3 then 2 then 1). So far I have:

(define (triangle n)
  (cond
    [(zero? n) empty]
    [else (cons n (triangle (sub1 n)))]))

But that only gives me (list 5 4 3 2 1). Please keep note that this uses only the basic of scheme beginner lists and abbreviations. Thanks!

like image 891
James Lalonde Avatar asked Apr 12 '26 17:04

James Lalonde


1 Answers

It's always a good idea to split a complex problem in simpler, shorter subparts. In this case, we can simplify the general solution by first writing solutions to subproblems, like this:

  1. First, build a procedure that creates a list of strings, where a string is "*****" or "****" or ... or "*"
  2. Second, write a repeat helper procedure that given a string and a number, repeats the string that many times - for example: (repeat "*" 3) will return "***"

It's easy to see how the first subproblem can be expressed in terms of the second one. Because this looks like a homework, you shouldn't be asking for complete solutions here. It'll be more useful for you to reach the answer by yourself, here's the general idea, fill-in the blanks:

(define (triangle n)
  (cond [<???> <???>]                 ; if n is zero return the empty list: '()
        [else                         ; otherwise
         (cons <???>                  ; cons n repetitions of * (using `repeat`)
               (triangle <???>))]))   ; and advance the recursion

(define (repeat str n)
  (cond [<???> <???>]                 ; if n is zero return the empty string: ""
        [else                         ; otherwise
         (string-append <???>         ; append the given string
             (repeat <???> <???>))])) ; and advance the recursion

If you look at it carefully, both procedures share exactly the same structure. What changes is the value returned in the base case (an empty list and an empty string) and the procedure used for sticking together the partial answers (cons and string-append).

like image 200
Óscar López Avatar answered Apr 15 '26 10:04

Óscar López