[racket] Beginner question cons vs list vs ?

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sun Apr 28 14:45:13 EDT 2013


Your base case must be a list (Contracts and tests are optional):

#lang racket

;; -----------------------------------------------------------------------------
;; a simple fizzbuzz function 

(provide 
 (contract-out
  ;; given a natural number, produce the fizz/buzz list for it
  (fizzbuzz (-> natural-number/c (listof (or/c number? symbol?))))))

(module+ test 
  (require rackunit))

(define (printer num)
  (cond((and (= 0 (remainder num 3)) (= 0 (remainder num 5))) 'fizzbuzz)
       ((= 0 (remainder num 3)) 'fizz)
       ((= 0 (remainder num 5)) 'buzz)
       (else num)))

(define (fizzbuzz limit)
  (define (helper current limit)
    (cond ((>= current limit) (list (printer limit)))
          (else (cons (printer current) (helper (+ 1 current) limit)))))
  (helper 1 limit))

(module+ test
  (require (submod ".."))
  (check-equal? (fizzbuzz 10) '(1 2 fizz 4 buzz fizz 7 8 fizz buzz)))

If you write down 'contracts' (even informally) they may help you formulate what to produce. If you're insecure, express contracts within the language. 






On Apr 28, 2013, at 2:23 PM, Leonard Cuff wrote:

> I'm trying to teach myself scheme (racket) and decided to try writing  fizzbuzz.  My program mostly works, but instead of getting a single list, I get a list with a dot before the last list item, which I assume means I've got a 'cons' at the end rather than just one list. What am I doing wrong?  Any general comments on style or approach also welcome.
> 
> Thanks,
> 
> Leonard
> 
> #lang racket
> 
> 
> (define (printer num)
>   (cond((and (= 0 (remainder num 3)) (= 0 (remainder num 5))) 'fizzbuzz)
>        ((= 0 (remainder num 3)) 'fizz)
>        ((= 0 (remainder num 5)) 'buzz)
>        (else num)))
> 
> (define (fizzbuzz limit)
>   (define (helper current limit)
>     (cond ((>= current limit) (printer limit))
>           (else (cons (printer current)
>                 (helper (+ 1 current) limit)))))
>   (helper 1 limit))
> 
> (fizzbuzz 10)
> 
> '(1 2 fizz 4 buzz fizz 7 8 fizz . buzz)
> > 
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130428/869b678e/attachment.html>

Posted on the users mailing list.