iyi

Playground · Generics · 31 of 33

bounds

Bounds: a generic that asks its type parameter for a trait.

samples/tour/bounds.iyi · bounds.wasm · 126 KB
# Bounds: a generic that asks its type parameter for a trait.

trait Priced
  abstract def price : Int32
end

struct Book
  def initialize(@price : Int32)
  end
end

struct Coffee
  def initialize(@price : Int32)
  end
end

impl Priced for Book
  def price : Int32
    @price
  end
end

impl Priced for Coffee
  def price : Int32
    @price
  end
end

# `T : Priced` says: any T, as long as it implements Priced. The bound is
# checked where the call is made, so `total([1, 2])` would not compile.
def total(items : Array(T)) : Int32 forall T : Priced
  items.sum { |item| item.price }
end

puts total([Book.new(120), Book.new(80)])
puts total([Coffee.new(45)])

def cheapest(items : Array(T)) : T forall T : Priced
  items.min_by { |item| item.price }
end

puts cheapest([Coffee.new(45), Coffee.new(30)]).price
output
Press Run.

recorded with iyi 0.18.0 (built on Crystal 1.22.0-dev [2a9653052] (2026-10-18)) · Linux 7.0.0-38-generic x86_64, QEMU Virtual CPU version 2.5+ · 2026-10-19

You can type in the pane: nothing here compiles, so what you type cannot run, and the page says which bytes it is running the moment the text stops being the recorded file. There is no standard input, no filesystem and no threads on this target, and one sample fails on purpose for exactly that reason.

Run executes bounds.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

Copy the program into bounds.iyi, change something, and run it. Only a compiler on your own machine can run what you wrote.

sh, after installing
$ iyi run bounds.iyi