你如何在 Scheme 中返回一个过程的描述? [英] How do you return the description of a procedure in Scheme?

查看:32
本文介绍了你如何在 Scheme 中返回一个过程的描述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的事情:

(define pair (cons 1 (lambda (x) (* x x))

如果我想返回对的前面对象,我这样做:

If I want to return the front object of the pair I do this:

(car pair)

它返回 1.但是当对象是一个过程时,我没有得到它的确切描述.换句话说:

And it returns 1. However when the object is a procedure I don't get the exact description of it. In other words:

(cdr pair)

返回 # 而不是 (lambda (x) (*x x)).

我该如何解决这个问题?

How do I fix this?

推荐答案

虽然一般情况下没有办法做到这一点,但您可以为您定义的过程装配一些东西来做到这一点.

Although there's no way to do this generally, you can rig up something to do it for procedures that you define.

  1. Racket structs 可以定义一个 prop:procedure 允许将结构作为一个过程来应用(调用).相同的结构可以保存函数定义的原始语法的副本.这就是下面的 sourced 结构所做的.

  1. Racket structs can define a prop:procedure that allows the struct to be applied (called) as a procedure. The same struct can hold a copy of your original syntax for the function definition. That's what the sourced struct is doing, below.

write-sourced 的东西只是为了让输出更干净(只显示原始的 sexpr,而不是其他结构字段).

The write-sourced stuff is simply to make the output cleaner (show only the original sexpr, not the other struct fields).

define-proc 宏使结构体的初始化变得更简单——您无需键入两次代码并希望它匹配.它会为您做到这一点.

The define-proc macro makes it simpler to initialize the struct -- you don't need to type the code twice and hope it matches. It does this for you.

<小时>

#lang racket

(require (for-syntax racket/syntax))

;; Optional: Just for nicer output
(define (write-sourced x port mode)
  (define f (case mode
              [(#t) write]
              [(#f) display]
              [else pretty-print])) ;nicer than `print` for big sexprs
  (f (sourced-sexpr x) port))

(struct sourced (proc sexpr)
        #:property prop:procedure (struct-field-index proc)
        ;; Optional: Just to make cleaner output
        #:methods gen:custom-write
        [(define write-proc write-sourced)])

;; A macro to make it easier to use the `sourced` struct
(define-syntax (define-proc stx)
  (syntax-case stx ()
    [(_ (id arg ...) expr ...)
     #'(define id (sourced (lambda (arg ...) expr ...)
                           '(lambda (arg ...) expr ...)))]))

;; Example
(define-proc (foo x)
  (add1 x))

(foo 1) ; => 2
foo     ; => '(lambda (x) (add1 x))

这篇关于你如何在 Scheme 中返回一个过程的描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆