typestar

vowel_count.wat in WebAssembly

Walk a passage in a data segment byte by byte and tally its vowels.

;; Count the vowels in a passage baked into linear memory.
(module
  (memory 1)
  (data (i32.const 0) "the rain in maine falls mainly on the plain")
  (global $length i32 (i32.const 43))

  ;; ASCII codes: a 97, e 101, i 105, o 111, u 117.
  (func $is_vowel (param $c i32) (result i32)
    (i32.or
      (i32.or
        (i32.or
          (i32.eq (local.get $c) (i32.const 97))
          (i32.eq (local.get $c) (i32.const 101)))
        (i32.or
          (i32.eq (local.get $c) (i32.const 105))
          (i32.eq (local.get $c) (i32.const 111))))
      (i32.eq (local.get $c) (i32.const 117))))

  ;; Walk the passage byte by byte and tally.
  (func $count (export "count_vowels") (result i32)
    (local $i i32)
    (local $total i32)
    (block $done
      (loop $scan
        (br_if $done (i32.ge_s (local.get $i) (global.get $length)))
        (local.set $total
          (i32.add
            (local.get $total)
            (call $is_vowel (i32.load8_u (local.get $i)))))
        (local.set $i (i32.add (local.get $i) (i32.const 1)))
        (br $scan)))
    (local.get $total))

  (func (export "main") (result i32)
    (call $count)))

How it works

  1. The (data ...) segment bakes 43 bytes of text at address 0.
  2. $is_vowel ors together five i32.eq tests against ASCII codes.
  3. The scan loop adds the 0-or-1 answer straight into the total: 14.

Keywords and builtins used here

The run, in numbers

Lines
35
Characters to type
959
Tokens
218
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 218 seconds.

Type this snippet

Step 3 of 3 in Encore, step 28 of 28 in Language basics.

← Previous