The language / Blocks
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
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:
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:
var total = 0
const prices = [3, 5]
prices.each do (price)
total = total + price
end
print(total) # prints 8Variables 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:
| Method | The block gets | The block returns | The result |
|---|---|---|---|
items.each | each item | nothing | nil |
items.map | each item | the new value (declared: do (n): Int) | a new array |
items.filter | each item | true to keep the item | a new array |
items.find | each item | true for a match | the first match, or nil |
items.any | each item | true or false | true if any block returned true |
items.all | each item | true or false | true if every block returned true |
items.sort | each item | what to sort by | a new array, sorted |
items.sum | each item | an Int or a Float | them added up |
items.min, items.max | each item | an Int, a Float, a String or a Time | the least or the most, or nil |
items.average | each item | an Int or a Float | their average, a Float, or nil |
items.tally | each item | an Int or a String | a hash: each value, and how many gave it |
items.group | each item | an Int, a String or an enum's value | the items in groups: each value, and the items that gave it |
hash.each | each key and value | nothing | nil |
Array blocks may also ask for the index, counting from 0:
const names = ["Ada", "Grace"]
names.each do (name, index)
print("#{index}: #{name}")
end
# prints 0: Ada
# prints 1: Gracereturn 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:
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 3map'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:
const numbers: [Int] = []
const labels = numbers.map do (n): String
return "#{n}"
end
print(labels.length) # prints 0Sorting 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.
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}sortkeeps the order of items it finds equal, so the lastsortsays most, and an earlier one breaks its ties. Numbers sort by value, Strings by character code ("B"before"a"), Booleansfalsefirst, Times by when they are, andnilfirst (last when descending).sumof no items is0(or0.0);min,maxandaverageof none arenil, so check before using them.tally's hash has each value in the order it first appeared.items.limit(3),items.skip(3)anditems.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:
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: withlength, 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:
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(...):
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 3count_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). Otherwisex.each docould 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:
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 3walk 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:
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 []
endHere 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.