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, msg_id: MessageId) extends NeedsReply 
    derives JsonDecoder 

case class EchoOk(echo: String, in_reply_to: MessageId, `type`: String = "echo_ok")
    extends Sendable,
      Reply             
    derives JsonEncoder 

Note

Refer to Maelstrom documentation for more information on the standard message fields like msg_id, type, in_reply_to etc

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: ZIO[MaelstromRuntime, Nothing, Unit] =
    receive[Echo](msg => reply(EchoOk(echo = msg.echo, in_reply_to = msg.msg_id))) 
}

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

Note

Source code for this example can be found on Github