Skip to the page
The language / Blocks

Start here01

The language02

Programs and the world03

Kiln04

02 The language / 10

Blocks

Code given to a method to run for each element: each, map, filter, find, any and all.

Most work on a collection is one step repeated for every element: print it, add it to a total, keep it or leave it out. With a block you write only that step, and the method you give it to does the walking. This page shows how blocks are written, the built-in methods that take them, and how methods of your own can take one too.

Writing a block

A block is code passed to a method, which runs it for each element. Here each runs its block once per number, and map collects what its block returns into a new array:

each-and-map.hem
const numbers = [1, 2, 3, 4]

numbers.each do (n)
  print(n)
end

# prints 1
# prints 2
# prints 3
# prints 4

const doubled = numbers.map do (n): Int
  return n * 2
end

print(doubled) # prints [2, 4, 6, 8]

A block starts with do, then its parameters in parentheses, and ends with end on its own line. The body starts on the next line. Parameters have no types: they come from the collection. They are constants, like method parameters.

A block can use and change the variables around it, which is how it hands results back to the code that called the method:

change-outside-variable.hem
var total = 0
const prices = [3, 5]

prices.each do (price)
  total = total + price
end

print(total) # prints 8

Variables declared inside a block exist only inside it. After a block's end, the line must end, so store a result in a variable before using it further.

The methods that take blocks

Arrays and hashes come with these. Each one asks its block a different question, and does something different with the answers:

MethodThe block getsThe block returnsThe result
items.eacheach itemnothingnil
items.mapeach itemthe new value (declared: do (n): Int)a new array
items.filtereach itemtrue to keep the itema new array
items.findeach itemtrue for a matchthe first match, or nil
items.anyeach itemtrue or falsetrue if any block returned true
items.alleach itemtrue or falsetrue if every block returned true
items.sorteach itemwhat to sort bya new array, sorted
items.sumeach iteman Int or a Floatthem added up
items.min, items.maxeach iteman Int, a Float, a String or a Timethe least or the most, or nil
items.averageeach iteman Int or a Floattheir average, a Float, or nil
items.tallyeach iteman Int or a Stringa hash: each value, and how many gave it
items.groupeach iteman Int, a String or an enum's valuethe items in groups: each value, and the items that gave it
hash.eacheach key and valuenothingnil

Array blocks may also ask for the index, counting from 0:

each-with-index.hem
const names = ["Ada", "Grace"]

names.each do (name, index)
  print("#{index}: #{name}")
end

# prints 0: Ada
# prints 1: Grace

return in a block

return ends the current run of the block, never the method around it. What a block returns is its answer for that one element.

In each, use continue to skip to the next item and break to stop early. return is an error there, because each's block gives no value. In the other methods, the block must return a value on every path:

filter-and-find.hem
const numbers = [1, 2, 3, 4]

const evens = numbers.filter do (n)
  return n % 2 == 0
end

print(evens) # prints [2, 4]

const first_big = numbers.find do (n)
  return n > 2
end

print(first_big) # prints 3

map's block declares what it returns, after the parameters. That way the result has a known type even for an empty array, where the block never runs:

map-declares-its-type.hem
const numbers: [Int] = []

const labels = numbers.map do (n): String
  return "#{n}"
end

print(labels.length) # prints 0

Sorting and figures

sort and the figures ask the block for a value from each item: what to sort by, or what to add up, compare or count.

sorting-and-figures.hem
record Line
  name: String
  price: Int
  quantity: Int
end

const lines = [
  new Line(name: "Scarf", price: 40, quantity: 2),
  new Line(name: "Coat", price: 300, quantity: 1),
  new Line(name: "Socks", price: 12, quantity: 2),
]

const cheapest_first = lines.sort do (line)
  return line.price
end

print(cheapest_first[0].name) # prints Socks

const dearest_first = lines.sort(descending: true) do (line)
  return line.price
end

print(dearest_first[0].name) # prints Coat

const total = lines.sum do (line)
  return line.price * line.quantity
end

print(total) # prints 404

const most = lines.max do (line)
  return line.quantity
end

print(most) # prints 2

const by_quantity = lines.tally do (line)
  return line.quantity
end

print(by_quantity) # prints {2: 2, 1: 1}
  • sort keeps the order of items it finds equal, so the last sort says most, and an earlier one breaks its ties. Numbers sort by value, Strings by character code ("B" before "a"), Booleans false first, Times by when they are, and nil first (last when descending).
  • sum of no items is 0 (or 0.0); min, max and average of none are nil, so check before using them.
  • tally's hash has each value in the order it first appeared.
  • items.limit(3), items.skip(3) and items.first() take part of an array without a block.

The same methods, with the same blocks, work on a query of the database package's tables, and mean the same there.

Groups

group puts the items in groups by what the block gives. Each group has its key, what its items gave, and its rows, those items:

groups.hem
record Line
  product: String
  size: String
  quantity: Int
end

const lines = [
  new Line(product: "Scarf", size: "M", quantity: 2),
  new Line(product: "Coat", size: "L", quantity: 1),
  new Line(product: "Scarf", size: "S", quantity: 3),
]

const by_product = lines.group do (line)
  return line.product
end

print(by_product[0].key)         # prints Scarf
print(by_product[0].rows.length) # prints 2

const sold = by_product.map do (group): String
  const quantity = group.rows.sum do (line)
    return line.quantity
  end

  const sizes = group.rows.map do (line): String
    return line.size
  end

  return "#{group.key}: #{quantity} sold, sizes: #{sizes.unique().length}"
end

print(sold) # prints ["Scarf: 5 sold, sizes: 2", "Coat: 1 sold, sizes: 1"]
  • Groups come in the order their keys first appear, and a group's rows keep their order. The groups are an array, sorted, filtered and mapped as any.
  • A key is an Int, a String or an enum's value, never nil.
  • unique() gives each value once, the first of each, in order: with length, how many different values there are.

Changing the collection inside a block

A block runs over the collection as it was when the method started. Changing the variable inside the block doesn't change the loop, so it can't run on forever or skip elements:

changing-the-collection-inside-a-block.hem
var items = [1, 2]

items.each do (n)
  items.push(n * 10)
end

print(items) # prints [1, 2, 10, 20]

Blocks for methods of your own

A method of your own can take a block too. It says so after its signature, and runs the block with yield(...):

count-where.hem
def count_where(items: [Int]): Int do (Int): Boolean
  var count = 0

  items.each do (item)
    if yield(item)
      count = count + 1
    end
  end

  return count
end

var looked_at = 0

const big = count_where([1, 5, 9]) do (n)
  looked_at = looked_at + 1

  return n > 3
end

print(big)       # prints 2
print(looked_at) # prints 3

count_where decides when the block runs and what to do with its answers; the caller decides the question. The block also counts its runs in looked_at, a variable around the call.

The block's type comes after the parameters and the return type. do (Int): Boolean gives the types the block gets, then what it gives back, if anything, with ! if it can fail. A block that gets nothing is do. A method takes at most one block.

yield(...) runs the block with those values, and gives what it returns. The method yields as often as it likes, or never. yield in a method that takes no block is an error.

The caller gives the block as for built-in methods: do (names) ... end after the call. Its parameters get their types from the method, and it uses and changes the variables around it. A method whose only parameter is its block is called without parentheses: tree.walk do (value).

Inside the block, return ends the current run: with a value on every path if the block gives one, bare if it gives nothing. break and continue only work in loops inside the block, since the method decides how often it runs.

  • A method that changes its object has it while it runs, so its block can't use the variable that holds it.
  • A method of your own that takes a block isn't named like a built-in one that does (each, map, filter, find, any, all, where). Otherwise x.each do could mean either, and only the types could tell which.

Passing a block on

A block is never a value: it can't be stored, returned or passed on. To hand it on, give the other method a block that yields. yield runs the block of the method its code is in, even inside another block:

tree-walk.hem
class Tree
  readable const value: Int
  readable const children: [Tree]

  def walk() do (Int)
    yield(self.value)

    self.children.each do (child)
      child.walk do (value)
        yield(value)
      end
    end
  end
end

const leaf = new Tree(value: 2, children: [])
const tree = new Tree(value: 1, children: [leaf, new Tree(value: 3, children: [])])

tree.walk do (value)
  if value == 2
    return
  end

  print(value)
end

# prints 1
# prints 3

walk yields its own value, then walks each child with a block of its own, which yields each value it gets on to walk's caller. The caller's return ends only that run of its block, so 2 is skipped and 3 still prints.

Blocks that can fail

A block whose type has ! fails with try or return failure(...), and the method runs it with try yield(...) (or rescue). In a block that can't fail, they're errors. Failures covers try and rescue in full:

failing-block.hem
def parse_all(texts: [String]): [Int]! do (String): Int!
  var numbers: [Int] = []

  texts.each do (text)
    numbers.push(try yield(text))
  end

  return numbers
end

def numbers_in(texts: [String]): [Int]!
  return try parse_all(texts) do (text)
    return try Int(text)
  end
end

const bad = numbers_in(["3", "x"]) rescue error
  print(error.message) # prints "x" isn't a whole number, so it can't become an Int

  return []
end

Here the block's try Int(text) fails on "x", try yield(text) passes the failure out of parse_all, and numbers_in passes it on to the rescue.