[racket] [racket-dev] Please help me to fix the code

From: Rodolfo Carvalho (rhcarvalho at gmail.com)
Date: Wed Jun 1 01:02:22 EDT 2011

[Moving the thread to the users mailing list]

Yingjian,

Good to see you persevering and getting it done! Congratulations.

Before I reasoned about your code, just looking at its shape was enough to
imagine it was not properly indented.
You can use and abuse of DrRacket for your on good.

Using the shortcut CTRL+I let's you reindent all of your code, which gives
this:

#lang racket
(define (count-matches s l)
  (define (addone s l x)
    (cond
      [(empty? l) x]
      [(equal? s (first l)) (addone s (rest l) (+ 1 x))]
      [else (addone s (rest l) x)]))
  (addone s l 0))


The change in indentation makes clear that you're defining an auxiliary
function and the result of calling count-matches is that of calling (addone
s l 0).

BTW "addone" doesn't really sound to me to describe what the function is
doing -- it not always "adds one".


Look how a similar implementation is possible without an inner auxiliary
function:

#lang racket
(define (count-matches s l)
  (cond
    [(empty? l) 0]
    [(equal? s (first l)) (add1 (count-matches s (rest l)))]
    [else (count-matches s (rest l))]))

(count-matches 'x '())      ;   should be 0
(count-matches 'x '(a b x)) ;   should be 1
(count-matches 'x '(x b x)) ;   should be 2


[]'s

Rodolfo Carvalho


On Wed, Jun 1, 2011 at 01:37, Yingjian Ma <yingjian.ma1955 at gmail.com> wrote:

> I finished it.  The purpose of the function is to count the occurrance of a
> letter in a list.  Ex:
>
> (count-matches 'x '())   should be 0
> (count-matches 'x '(a b x))   should be 1
> (count-matches 'x '(x b x))   should be 2
>
> The keywords I can use are limited.   Thank you all for the help.  Another
> I need to write is to remove duplicated items from the list.
>
> It seems that under cond, one condition can only take one expression.  What
> can I do if I want to do two statements?
>
> Here is the code.
>
> (define (count-matches s l)
>   (define (addone s l x)
>      (cond
>      [(empty? l) x]
>      [(equal? s (first l)) (addone s (rest l) (+ 1 x))]
>      [else (addone s (rest l) x)]))
>      (addone s l 0))
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20110601/27c1891d/attachment.html>

Posted on the users mailing list.