方案语言案例有多个测试条件?

时间:2014-02-02 20:16:30

标签: functional-programming scheme

我正在尝试做的事情如下所示:伪代码:

case (test0, test1)
  begin
    (false,false): statement 0;
    (false,true): statement 1;
    (true,false): statement 2;
    (true,true): statement 3;
  end

如何在方案中使用案例条件?问题是该案例使用eqv?谓词,它似乎总是返回false(因为(eqv? '(#f . #f) '(#f . #f))计算为#f)。会欣赏在方案中表达上述模式的任何合理简洁的方式(除了明显将其分解为嵌套if条件)。

编辑:下面的有效答案让我稍微重新调整了一下我的查询:经验丰富的策划者如何编码上述模式?

3 个答案:

答案 0 :(得分:1)

一种说明方法的方法:

(case (+ (if test0 10 0) (if test1 1 0))
  ((11) …)
  ((10) …)
  ((01) …)
  ((00) …))

我将如何实际执行此操作...如果test0test1之间的重要性存在任何不对称,我只需先将if与最重要的test一起使用。因此,假设test0更重要:

(if test0
    (if test1
        …  ;; (and test0 test1)
        …) ;; (and test0 (not test1))
    (if test1
        …   ;; …
        …)) ;; … 

如果重要性没有任何差别,那么:

(cond ((and test0 test1) …)
      ((and test0 (not test1)) …)
      …)

如果它是带有两个变量的常见模式,那么我将定义一个宏,它允许我在test0和test1的词法绑定中指定四个实体:

(define-syntax if-two-way
  (syntax-rules (tt tf ft ff)
    ((if-two-way test0 test1
       (tt btt1 btt …)
       (tf btf1 btf …)
       (ft bft1 bft …)
       (ff bgg1 bff …))
     (let ((t0 test0) (t1 test1))
       (if t0
           (if t1
               (begin btt1 btt …)
               (begin btf1 btf …))
           …))))))

答案 1 :(得分:1)

这似乎非常适合Racket的match

(define (test pair)
  (match pair
    ['(#f . #f) "statement 1"]
    ['(#f . #t) "statement 2"]
    ['(#t . #f) "statement 3"]
    ['(#t . #t) "statement 4"]
    [else (error "unknown expression:" pair)]))

例如:

(test '(#t . #f))
=> "statement 3"

(test (cons (= 0 0) (= 1 1)))
=> "statement 4"

(test '(a . b))
=>  unknown expression: (a . b)

答案 2 :(得分:0)

使用condequal?

更容易
(define (test pair)
  (cond
    ((equal? pair '(#f . #f)) "statement 0")
    ((equal? pair '(#f . #t)) "statement 1")
    ((equal? pair '(#t . #f)) "statement 2")    
    ((equal? pair '(#t . #t)) "statement 3")
    (else                     "wot?")))
相关问题