【问题标题】:How to return string containing evaluated arguments of procedure?如何返回包含过程评估参数的字符串?
【发布时间】:2012-03-25 18:34:21
【问题描述】:

使用 Racket,我想设计一个过程,将一个二进制运算和两个任意类型的参数 a 和 b 作为其输入,计算参数的二进制运算,并返回一个描述计算结果的字符串。例如,如果我的过程被称为 foo,那么

(foo + 1 2)
(foo cons 'bar empty)

会回来

The + of 1 and 2 is: 3
The cons of 'bar and empty is: (bar)

我的代码看起来像

(define (foo op a b)
    (let ((result (op a b)))
      (display
       (string-append
        "The "
        (arg->string op)
        " of "
        (arg->string a)
        " and " 
        (arg->string b)
        " is: "
        (arg->string result)
        ))))

是否可以构造一些操作 arg->string 来执行我想要的操作(即,在转换为字符串之前评估其参数?)。 只需构造一个字符串或在其中引用参数过程的主体返回文字结果,即“op”或“op”而不是“+”或“+”。

感谢任何帮助。

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    这个解决方案是我想到的最简单的:

    (define (foo op a b)
      (printf "The ~s of ~s and ~s is: ~s\n"
              (object-name op) a b (op a b)))
    

    看看这是否适合你:

    (foo + 1 2)
    > The + of 1 and 2 is: 3
    
    (foo cons 'bar empty)
    > The cons of bar and () is: (bar)
    

    【讨论】:

    • @thesook 好消息!就在您接受我的回答之后,我找到了一种方法来显示您想要的程序名称。看看我更新的答案! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 2011-11-17
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多