Skip to content

Instantly share code, notes, and snippets.

@atacratic
Created July 19, 2021 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atacratic/f672a9b38fcc484786892eb5e08c7112 to your computer and use it in GitHub Desktop.
Save atacratic/f672a9b38fcc484786892eb5e08c7112 to your computer and use it in GitHub Desktop.
Playing with the Unison distributed API - a `Cell` type: state sharing between tasks
-- Contains a piece of state which can be written and read from different tasks.
type Cell a = Cell (Channel (CellProto a))
type CellProto a = Read (Channel a) | Write a
example = 'let
c = Cell.new 1
f = 'let
Cell.write 2 c
g = 'let
Cell.read c
tf = Fork.detach f
tg = Fork.detach g
task.await tf
task.await tg
Cell.read : Cell a ->{Channels} a
Cell.read c =
(Cell reqChannel) = c
rspChannel = Channels.new
Channels.send (Read rspChannel) reqChannel
rsp = Channels.receive rspChannel
Channels.close rspChannel
rsp
Cell.write : a -> Cell a ->{Channels} ()
Cell.write a c =
(Cell reqChannel) = c
Channels.send (Write a) reqChannel
Cell.new : a ->{Channels, Fork t Channels} Cell a
Cell.new initial =
receiveChannel = Channels.new
goCell : a -> Void
goCell state =
match Channels.receive receiveChannel with
Read rspChannel ->
Channels.send state rspChannel
goCell state
Write newState ->
goCell newState
Fork.detach '(goCell initial)
Cell receiveChannel
-- this is just a toy: haven't thought about failure, concurrent
-- access, or cell termination. Writes should probably have an ack.
---
I found and typechecked these definitions in ~/unison/scratch.u. If
you do an `add` or `update`, here's how your codebase would change:
⍟ These new definitions are ok to `add`:
type Cell a
type CellProto a
Cell.new : a ->{Channels, Fork t Channels} Cell a
Cell.read : Cell a ->{Channels} a
Cell.write : a -> Cell a ->{Channels} ()
example : '{Channels, Remote t, Fork t Channels} Nat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment