EK9 idioms: guards, coalescing, pipelines and dispatchers

The complete source of forAI_idioms.ek9, compiled by the EK9 compiler. Shown on forAI.html.

#!ek9
defines module site.forAI.idioms

  defines function

    getValue() as pure
      <- rtn as String: "ready"

    computeIfNeeded() as pure
      <- rtn as String: "computed"

    process()
      -> status as String
      Stdout().println(`Processing ${status}`)

    isValid() as pure
      -> item as Integer
      <- rtn as Boolean: item > 0

    transform() as pure
      -> item as Integer
      <- rtn as Integer: item * 2

    useAGuard()
      // Check and use in one expression
      if result <- getValue()
        process(result)

    useCoalescing()
      -> defaultValue as String
      <- answer as String?
      existingVar <- getValue()

      // Use default if unset (?: gives the right when the left is unset)
      result <- getValue() ?: defaultValue

      // Fill an unset variable (assign-if-unset - computeIfNeeded() runs only if needed)
      existingVar :=? computeIfNeeded()

      answer: `${result}\n${existingVar}`

    usePipeline()
      -> items as List of Integer
      <- answer as List of Integer?

      // Transform and collect
      result <- cat items
        | filter by isValid
        | map with transform
        | collect as List of Integer

      answer: result

  defines class

    Event as abstract
      default operator ?

    OrderPlaced extends Event
      reference as String: String()

      OrderPlaced()
        -> reference as String
        this.reference :=: reference

      reference() as pure
        <- rtn as String: reference

      default operator ?

    OrderCancelled extends Event
      default operator ?

    // A dispatcher is a METHOD - declare it in a class
    Notifier
      // Declare the dispatcher - its body is the fallback
      describe() as dispatcher
        -> event as Event
        <- text as String: "Unknown event"

      // Implement per concrete type
      describe()
        -> placed as OrderPlaced
        <- text as String: `Order ${placed.reference()} placed`

  defines program

    Idioms()
      stdout <- Stdout()
      useAGuard()
      stdout.println(useCoalescing("default"))
      stdout.println($usePipeline([-1, 1, 2]))

      notifier <- Notifier()
      events as List of Event: [OrderPlaced("A-1"), OrderCancelled()]
      for event in events
        stdout.println(notifier.describe(event))

Download forAI_idioms.ek9

Output

Processing ready
ready
ready
[2, 4]
Order A-1 placed
Unknown event