如此奮鬥了一天,卻未及要害,殘念。


import candygram as cg

def rpc(pid, req, res=[]):
  def receive(fun = cg.Receiver()):
    fun[cg.Any] = lambda m: m, cg.Message
    res.append(fun())
  pid | (cg.spawn(receive), req)
  while( not res): pass
  return res.pop()

def loop():
  fun = cg.Receiver()
  def rect  (( pid, (fun, width, ht) )): pid | width * ht
  def circle(( pid, (fun, R)         )): pid | 3.14159 * R * R
  def other (( pid, (args)           )): pid | ('error', args)
  fun[ cg.Process, ('rect', int, int)] = rect,   cg.Message
  fun[ cg.Process, ('circle', int)   ] = circle, cg.Message
  fun[ cg.Process, cg.Any            ] = other,  cg.Message
  for r in fun: pass

if __name__ == '__main__':
  import time
  proc = cg.spawn(loop)
  print rpc(proc, ('rect', 6, 8))
  print rpc(proc, ('circle', 6))
  print rpc(proc, ('joke'))
  time.sleep(0.2) # Give the proc a chance to print before termination

參閱 "Programming Erlang" Ch8.3 area_server1.erl