trueagi-io / metta-morph

Metta-morph (from Metamorphosis): Macro-based MeTTa to (Chicken) Scheme translator.
MIT License
7 stars 1 forks source link

Parallel superpose #22

Open patham9 opened 10 months ago

patham9 commented 10 months ago

An attempt I tried a few weeks ago which worked out and I forgot to document (OS-process-based ambivalence to let one easily make use of CPU resources)

(import (chicken process) (chicken string) (chicken file posix) amb)

(define-syntax hyperpose
  (syntax-rules ()
    ((_ arg1 arg2)
     (receive (pipefd0 pipefd1) (create-pipe)
              (let ((pid (process-fork)))
                   (if (eq? pid 0)
                       (begin (write arg1 (open-output-file* pipefd1))
                              (exit 0)) ;child is done
                       (let* ((res1 arg2) ;get to work before waiting for child to return result
                              (res2 (read (open-input-file* pipefd0))))
                             (amb res1 res2))))))))

;example:
(define (test x) (list 2 x (+ 2 x)))
(display (amb-collect (hyperpose (test 1) (test 2))))
(newline)

This is just an example, forking has some time overhead so use only if you have computationally expensive branches which should be able to be explored with different CPU cores!

patham9 commented 10 months ago

For mettamorph.scm the repeated amb import is not needed and the arguments should be wrapped into auto-list1:

(import (chicken process) (chicken string) (chicken file posix))

(define-syntax hyperpose
  (syntax-rules ()
    ((_ arg1 arg2)
     (receive (pipefd0 pipefd1) (create-pipe)
              (let ((pid (process-fork)))
                   (if (eq? pid 0)
                       (begin (write (auto-list1 arg1) (open-output-file* pipefd1))
                              (exit 0)) ;child is done
                       (let* ((res1 (auto-list1 arg2)) ;get to work before waiting for child to return result
                              (res2 (read (open-input-file* pipefd0))))
                             (amb res1 res2))))))))

TODO accept list (tuple) as argument which can have more than 2 items.

patham9 commented 10 months ago

An initial useful version is in master now https://github.com/trueagi-io/metta-morph/commit/69ae8bf482289a439d483059111167ff38303bf3