-1

I think I read somewhere that you could bind multiple definitions to a single name in scheme. I know I might be using the terminology incorrectly. By this I mean it is possible to do the following (which would be really handy to defining an operator)?

I believe I read something like this (I know this is not real syntax)

(let ()
define operator "+"
define operator "-"
define operator "*"
define operator "/"))

I want to test another variable against every operator.

4

2 回答 2

1

我不确定你在问什么。您想要一个可以处理不同类型参数的过程吗?

(define (super-add arg1 arg2)
  (cond ((and (string? arg1) (string? arg2))
         (string-append arg1 arg2))
        ((and (number? arg1) (number? arg2))
         (+ arg1 arg2))
        (else
          (error "UNKNOWN TYPE -- SUPER-ADD"))))

(super-add "a" "b") => "ab"
(super-add 2 2) => 4

您对消息传递感兴趣吗?

(define (math-ops msg)  ;<---- returns a procedure depending on the msg
  (cond ((eq? msg 'add) +)
        ((eq? msg 'sub) -)
        ((eq? msg 'div) /)
        ((eq? msg 'multi) *)
        (else
          (error "UNKNOWN MSG -- math-ops"))))

((math-ops 'add) 2 2) => 4
((math-ops 'sub) 2 2) => 0

let绑定的正确语法也是:

(let (([symbol] [value])
      ([symbol] [value]))
   ([body]))

(let ((a 2)
      (b (* 3 3)))
   (+ a b))

 => 11

如果您不澄清您正在尝试做什么,将很难提供更多帮助。

编辑:在您发表评论后,我对您正在寻找的东西有了更好的了解。无法按照您的意思将多个值绑定到同一个名称。您正在寻找一个谓词,它会告诉您正在查看的东西是否是您的运算符之一。从您的评论看来,您将接受一个字符串,这就是它的基础:

(define (operator? x)
    (or (string=? "+" x) (string=? "-" x) (string=? "*" x) (string=? "/" x)))

如果您要接收单个字符串,则需要将其拆分为较小的部分。Racket 有一个内置的程序regexp-split可以为你做这件事。

(define str-lst (regexp-split #rx" +" [input str]))
于 2012-05-06T01:32:47.223 回答
0

您可能指的是values“将参数传递给延续”的构造。它可用于从函数返回多个值。例如,

(define (addsub x y)
  (values (+ x y) (- x y)))

(call-with-values
  (lambda () (addsub 33 12))
  (lambda (sum difference)
    (display "33 + 12 = ") (display sum) (newline)
    (display "33 - 12 = ") (display difference) (newline)))
于 2012-05-06T07:26:17.337 回答