The Big Book of Small EK9 Programs

Adapted from Al Sweigart's The Big Book of Small Python Projects: 81 Easy Practice Programs (No Starch Press, 2021; copyright © 2021 Al Sweigart), which he makes freely available under a Creative Commons Attribution-NonCommercial-ShareAlike licence at inventwithpython.com/bigbookpython. Changes were made: each program was ported from Python to EK9 and remodelled in EK9's idioms.

Project 72 — sPONGEcAsE

This is project 72 of the book, ported to EK9. Its chapter is still being written; until then, this page shows the port itself: a run of it, the whole program, and how it keeps to the original.

A sample run

The program is random, so the run fixes it by setting BIGBOOK_SEED=7.

Run it with:

BIGBOOK_SEED=7 ek9 spongecase.ek9 "Hello World"

It prints:

hElLo WoRlD

The program

#!ek9
defines module bigbook.spongecase

  defines constant

    ToggleChancePercent <- 90

  defines class

    //THE OUTPUT: everything the reader sees goes through here. The port shows no words of its
    //own, only the converted message, so there is no Say; the message is a program argument,
    //so there is no LineInput.
    Console
      stdout as Stdout: Stdout()

      //The conversion is computed, not worded: it is shown as the game made it.
      showConverted()
        -> converted as String
        stdout.println(converted)

      override operator ? as pure
        <- rtn as Boolean: true

  defines function

    //THE GAME: the conversion, with no output.

    //Each letter takes the current case, then the case flips nine times in ten. Anything
    //that is not a letter passes through unchanged and does not flip the case.
    spongeCased()
      ->
        message as String
        rng as Random
      <- rtn as String: ""

      useUpper <- false
      for character in message
        if character.isAlpha()
          rtn += useUpper <- character.upperCase() : character.lowerCase()
          if rng.next(1, 100) <= ToggleChancePercent
            useUpper: not useUpper
        else
          rtn += character

  defines function

    //THE source of randomness, copied unchanged from lib/RandomSource.ek9: SystemRandom(), or
    //SeededRandom(seed) when BIGBOOK_SEED holds a number (run-and-diff.sh sets it from seed.txt).
    randomSource()
      <- rtn as Random: SeededRandom(Integer(EnvVars().get("BIGBOOK_SEED"))) ?: SystemRandom()

  defines program

    //sPoNgEcAsE (Big Book project 72). Rewrites the message argument in sPoNgEcAsE, flipping the
    //case of its letters at random. The game decides; the Console shows it. The golden replays a
    //seeded run (seed.txt).
    SpongeCase()
      -> message as String
      console <- Console()
      rng <- randomSource()

      console.showConverted(spongeCased(message, rng))

About this port