How do you return the description of the procedure in the diagram?

Suppose I have something like this:

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

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

(car pair)

And it returns 1. However, when the object is a procedure, I do not get its exact description. In other words:

(cdr pair)

returns #<procedure>, not (lambda (x) (*x x)).

How to fix it?

+1
source share
2 answers

Although there is no way to do this, you can configure something to do this for the procedures that you define.

  • Racket struct prop:procedure, () . . , sourced, .

  • write-sourced - ( sexpr, ).

  • define-proc - , . .


#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))
+5

cons : 1 1; (lambda ...) . "" , quote :

> (define pair (cons 1 '(lambda (x) (* x x))
> (cdr pair)
(lambda (x) (* x x))
+1

Source: https://habr.com/ru/post/1544623/


All Articles