Erlang and Concurrency

Erlang is famous for its concurrency. Concurrent programming can be used to improve performance, gain scalability and fault-tolerance. BEAM is the virtual machine at the core of the Erlang Open Telecom Platform (OTP) which enables it to happen. By compiling Hamler to CoreErlang, we can essentially take advantage of Erlang VM.

  1. import Prelude
  2. import Data.List as L
  3. start :: IO ()
  4. start = do
  5. pid0 <- getSelf
  6. pids <- seqio [spawn $ loop (State pid0) | x <- [1..1000]]
  7. seqio [send j (Next i) | (i,j) <- (zip pids [last pids|L.init pids]) ]
  8. send (head pids) (Trans "great hamler! " 0)
  9. return ()
  10. data Message = Next Pid
  11. | Trans String Integer
  12. data State = State Pid
  13. handleMsg :: State -> Message -> IO State
  14. handleMsg (State pid) (Next p) = return (State p)
  15. handleMsg (State pid) (Trans str 1111) = return (State pid)
  16. handleMsg (State pid) (Trans str i) =
  17. do send pid (Trans str (i+1))
  18. pid0 <- getSelf
  19. println (show pid0 <> " -> " <> show pid <> ": " <> str <> show i)
  20. return (State pid)
  21. loop :: State -> IO ()
  22. loop s = receive v -> handleMsg s v >>= loop