← language reference

working with data

Start with a list or map. Transform it, ask questions, and print the result.

lesson 01

JSON: read and write data

JSON is a text format used to exchange data. json_parse turns that text into a map or list. Read a field with .name, then use json_stringify to turn your result back into text.

let person = json_parse("{\"name\":\"Ada\",\"score\":12}")
print(person.name)
person.score += 3
print(json_stringify(person))

expected output

Ada
{"name":"Ada","score":15}

Change the starting score to 20. The final score should be 23.

try json in playground →

lesson 02

Sorting: put a list in order

sort makes a new ordered list and leaves the original unchanged. reverse flips the order. slice(list, start, end) keeps items from start up to—but not including—end. Positions start at zero. |> passes each result to the next function.

let scores = [12, 3, 25, 8]
print(sort(scores))
scores |> sort |> reverse |> slice(0, 2) |> print
print(scores)

expected output

[3, 8, 12, 25]
[25, 12]
[12, 3, 25, 8]

Change slice(0, 2) to slice(0, 3) to keep the best three scores.

try sorting in playground →

lesson 03

Searching: ask a question

A predicate is a function that answers a question. find returns the first matching item, or nil when there is no match. any asks whether at least one item matches; every asks whether all items match. Only false and nil count as false in Lumen.

let scores = [3, 12, 25]
print(find(scores, fn(n) { n > 10 }))
print(any(scores, fn(n) { n > 20 }))
print(every(scores, fn(n) { n > 10 }))
print(find(scores, fn(n) { n > 100 }))

expected output

12
true
false
nil

Change the first question to n > 20. The first match becomes 25.

try searching in playground →

lesson 04

Maps: work with named values

A map stores values under names called keys. has checks whether a key exists—even if its value is nil. values returns all values. entries returns [key, value] pairs that you can walk through with for.

let stock = { apples: 3, pears: 2 }
print(has(stock, "apples"), has(stock, "oranges"))
print(values(stock))
for pair in entries(stock) {
  print(pair[0], pair[1])
}

expected output

true false
[3, 2]
apples 3
pears 2

Add oranges: 5 to the map, then run it again.

try maps in playground →