Search code examples
schemeguile

Guile/Scheme - redefine another module's internal function


Let's say I have the following two files:

;; demo.scm
(define-module (demo)
  #:export (f))

(define (g x) 1)
(define (f x) (g x))

... and in the same directory:

;; use-demo.scm
(add-to-load-path ".")
(use-modules (demo))

(define (g x) (+ x 1))
(display (f 5))
(newline)

Running use-demo.scm in Guile (2), I get the output 1. So it looks like the function f has 'closed over' the function g that's defined in module demo. Is there any way to get around this? I really want to use the version of g that I've redefined in use-demo.scm.


Solution

  • OK, just for the record, I did some research and am posting the solution to this specific problem in case it helps someone.

    The trick is to not redefine g locally, but rather to 'inject' the new function into the demo module's mapping of names to values.

    (add-to-load-path ".")
    (use-modules (demo))
    
    (module-define! (resolve-module '(demo)) 'g
      (lambda (x) (+ x 1)))
    
    (display (f 5))
    (newline)