2012-07-03 30 views
4

,因为昨天我一直在试图编程实现方案的特例声明,将做到以下几点:定义的语法使用的方案

(define (sort x) 
    (cond ((and (list? x) x) => (lambda (l) 
           (sort-list l))) 
     ((and (pair? x) x) => (lambda (p) 
         (if (> (car p) (cdr p)) 
          (cons (cdr p) (car p)) 
          p))) 
     (else "here"))) 

,而不是使用所有的和的和电导率的说法,我将有:

(define (sort x) 
    (scase ((list? x) => (lambda (l) 
           (sort-list l))) 
     ((pair? x) => (lambda (p) 
         (if (> (car p) (cdr p)) 
          (cons (cdr p) (car p)) 
          p))) 
     (else "here"))) 

我到目前为止做的,是这样的:

(define (sort x) 
    (scase (list? x) (lambda (l) 
         (sort-list l))) 
    (scase (pair? x) (lambda (p) 
         (if (> (car p) (cdr p)) 
          (cons (cdr p) (car p)) 
          p)))) 

与此代码:

(define-syntax scase 
    (syntax-rules() 
    ((if condition body ...) 
    (if condition 
     (begin 
      body ...))))) 

我想现在要做的,只是让scase语句有多个参数是这样的:

(scase ((list? (cons 2 1)) 'here) 
     ((list? '(2 1)) 'working)) 

,但我似乎无法弄清楚我如何能做到这一点。也许你们可以给我一点帮助?

在此先感谢;)

回答

2

如果这是在学习如何使用语法规则,那么忽略这个答案的练习。

我看到了一种方法来简化您开始的代码。

(define (sort x) 
    (cond ((list? x) 
      (sort-list x)) 
     ((pair? x) 
      (if (> (car x) (cdr x)) 
       (cons (cdr x) (car x)) 
       x))) 
     (else "here"))) 

由于所有的(and (list? x) x) => (lambda l ...所做的就是看是否x是一个列表,然后绑定lx,(因为#f不是一个列表,'()是不假,至少在球拍),你可以跳过所有这些,只需使用x。万一你不需要使用=>,在这种情况下,它不起作用。 =>是有用的,如果你想做一个测试,返回一些有用的,如果成功,否则#f

现在,如果你想使用宏,那么你将需要澄清你希望它做得更好一点。我认为这个案子已经做到了你想要的。您现有的宏只是if,所以我不确定如何扩展它。

2

我发现我的问题的解决,这里有云:

(define-syntax cases 
    (syntax-rules() 
    ((_ (e0 e1 e2 ...)) (if e0 (begin e1 e2 ...))) 
    ((_ (e0 e1 e2 ...) c1 c2 ...) 
    (if e0 (begin e1 e2 ...) (cases c1 c2 ...))))) 

谢谢大家反正:)

+0

如果这回答了你的问题,你应该[接受它](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 –

0

这里有一个解决方案:

#lang racket 

(require mzlib/defmacro) 

(define-syntax scase 
    (syntax-rules (else) 
    ((_ (else body1)) body1) 
    ((_ (condition1 body1) (condition2 body2) ...) 
    (if condition1 
     body1 
     (scase (condition2 body2) ...))))) 

(define (sort1 x) 
    ((scase ((list? x) (lambda (l) 
         (sort l <))) 
     ((pair? x) (lambda (p) 
         (if (> (car p) (cdr p)) 
          (cons (cdr p) (car p)) 
          p))) 
     (else (lambda (e) "here"))) 
    x)) 

它工作在DrRacket。我对您的解决方案做了三处更改。首先,我将sort程序重命名为sort1,因为排序内置在方案中(我在sort1中使用了它)。其次,我已经改变了sort1本身,以便给出的输入将被传递给scase返回的程序,您将直接获得排序结果。第三,我修改了scase语法扩展,以便它将接受else条件。

>(sort1 (list 3 1 2)) 
'(1 2 3) 

> (sort1 (cons 2 1)) 
'(1 . 2) 

> (sort1 'here) 
"here" 

我建议你阅读Kent Dybvig的“The Scheme Programming Language”。有关于句法扩展的整章。

+0

错误,你所做的只是重写cond(没有=>“功能”)。如果你在最终答案中用cond替换scase,代码将起作用。如果这就是你正在做的事情,那就说出来。 –