call/cc in Lua - Possible?

前端 未结 6 522
小鲜肉
小鲜肉 2020-12-13 19:46

The Wikipedia article on Continuation says:
\"In any language which supports closures, it is possible to write programs in continuation passing style an

6条回答
  •  我在风中等你
    2020-12-13 20:14

    Here's my cps-convert in scheme, just pass it every function you want to convert.

    (define (cps-convert function . functions)
      # Since "help" is called at 2 different places...
      (define (help) (error "syntax: (cps-convert f1 f2 ...)"))
      # Single function converter
      (define (convert func)
        # "name" contains the function's name prefixed with "cps-"
        (let ([name (string->symbol
                              (string-append "cps-" (symbol->string func)))])
          # Dirty hack to define "cps-*" in the global environment
         `(eval '(begin
                       # Necessary to prevent the function from being evaluated
                       (define ,name #f)
                                    # Magic
                       (set! ,name (lambda (k . args) (k (func args)))))
                     # Global environment
                     (interaction-environment))))
      # Prerequisite... Call help if condition not met
      (if (symbol? function)
          # function is a symbol
          (cond
            # If there is only one function to convert
            [(null? functions) (convert function)]
            # Else ensure every other "functions" are symbols and convert each
            [(every symbol? functions) (apply convert function functions)]
            # Oops! Condition not met!
            [else (help)])
          # Else clause from previous "if"
          (help)))
    

提交回复
热议问题