Skip to content

Instantly share code, notes, and snippets.

@schmalz
Created September 11, 2017 11:06
Show Gist options
  • Save schmalz/933e3c0d462c44f00e1bf301991c2342 to your computer and use it in GitHub Desktop.
Save schmalz/933e3c0d462c44f00e1bf301991c2342 to your computer and use it in GitHub Desktop.
Designing for Scalability with Erlang/OTP - Ch 8 - Coffee Supervisor - Pure LFE
(defmodule my-supervisor
(export
(start 2)
(init 1)
(stop 1)))
(defun start (name child-spec-list)
"Start a supervisor with `name` and `child-spec-list`."
(let ((pid (spawn (MODULE) 'init (list child-spec-list))))
(register name pid)
(tuple 'ok pid)))
(defun stop (name)
"Stop the supervisor with `name`."
(! name 'stop))
(defun init (child-spec-list)
"Initialise the supervisor's process."
(process_flag 'trap_exit 'true)
(loop (start-children child-spec-list)))
(defun start-children (child-spec-list)
(list-comp
((<- `#(,m ,f ,a) child-spec-list))
(tuple (element 2
(apply m f a))
(tuple m f a))))
(defun loop (child-list)
(receive
(`#(|EXIT| ,pid normal)
(loop (: lists keydelete pid 1 child-list)))
(`#(|EXIT| ,pid ,_reason)
(loop (restart-child pid child-list)))
('stop
(terminate child-list))))
(defun restart-child (pid child-list)
(let* ((`#(,_pid ,`#(,m ,f ,a))
(: lists keyfind pid 1 child-list))
(`#(ok ,new-pid)
(apply m f a)))
(: lists keyreplace pid 1 child-list (tuple new-pid (tuple m f a))))))
(defun terminate (child-list)
(: lists foreach (lambda (child)
(let ((`#(,pid ,_mfa) child))
(exit pid 'kill)))
child-list))
@schmalz
Copy link
Author

schmalz commented Sep 11, 2017

My first attempt at the pure LFE version of the Coffee Supervisor from Chapter 8.

@schmalz
Copy link
Author

schmalz commented Sep 11, 2017

Atoms that would require delimiting with single quotes in Erlang (e.g. 'EXIT') require delimiting with "pipe" characters (|) in LFE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment