Skip to content

Echo#

Info

This example is for Challenge #1: Echo

It demonstrates how to create a simple node that echoes messages back to the sender

Imports
import zio.json.{JsonEncoder, JsonDecoder}
import zio.ZIO
import com.bilalfazlani.zioMaelstrom.*

Here, we define the protocol of the node. It includes messages which the node can handle and messages it can send. Create data classes only for the body part of a maelstrom message. The top level fields (i.e. src, dest) are handled by the library

Message definitions
case class Echo(echo: String) derives JsonDecoder   
case class EchoOk(echo: String) derives JsonEncoder 

Note

Maelstrom documentation has information about core fields such as msg_id, type and in_reply_to. We don't need to define these fields in our message classes as they are handled by the framework automatically.

A node is defined by extending the MaelstromNode trait and providing a program value. The program value is a ZIO effect that defines the behavior of the node. The receive function is used to define a handler for incoming request messages.

Node application
object Main extends MaelstromNode { 
  val program = receive[Echo](msg => reply(EchoOk(msg.echo))) 
}

Using maelstrom DSL functions such as receive and reply requires MaelstromRuntime which is automatically provided by MaelstromNode.

Note

Source code for this example can be found on Github