| 📦 Turbo MoonBit cc1f595 k33g 13h ago | 1 | ///| |
| 2 | /// A greeting to print, and how many times to print it. |
| 3 | struct Greeting { |
| 4 | name : String |
| 5 | times : Int |
| 6 | } derive(Eq) |
| 7 | |
| 8 | ///| |
| 9 | /// Show is written out by hand rather than derived: `derive(Show)` is |
| 10 | /// deprecated, and this is the form the toolchain points at instead. |
| 11 | impl Show for Greeting with fn output(self, logger) { |
| 12 | logger.write_string("\{self.name} × \{self.times}") |
| 13 | } |
| 14 | |
| 15 | ///| |
| 16 | /// The tone a greeting is delivered in. |
| 17 | enum Tone { |
| 18 | Plain |
| 19 | Loud |
| 20 | Question |
| 21 | } derive(Debug) |
| 22 | |
| 23 | ///| |
| 24 | /// punctuate returns the mark a tone ends on. |
| 25 | fn punctuate(tone : Tone) -> String { |
| 26 | match tone { |
| 27 | Plain => "." |
| 28 | Loud => "!" |
| 29 | Question => "?" |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | ///| |
| 34 | /// greet prints one greeting, once per `times`. |
| 35 | /// |
| 36 | /// `tone` is a labelled argument with a default, so a call site may leave it |
| 37 | /// out — and when it does not, it reads as `greet(g, tone=Loud)`. |
| 38 | fn greet(g : Greeting, tone? : Tone = Plain) -> Unit { |
| 39 | for i in 0..<g.times { |
| 40 | println("Hello, \{g.name}\{punctuate(tone)} (\{i + 1} of \{g.times})") |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | ///| |
| 45 | fn main { |
| 46 | let g = { name: "MoonBit", times: 2, } |
| 47 | for tone in [Plain, Loud, Question] { |
| 48 | greet(g, tone~) |
| 49 | } |
| 50 | println("") |
| 51 | println("the greeting itself: \{g}") |
| 52 | } |