Skip to main content
Skip to content

Lesson 11 of 12

har, chuno and ikattha: map, filter and reduce

Hand a function to a list helper and let it do the looping: transform with har, pick with chuno, total up with ikattha.

10 min

Functions as inputs

In lesson 7 you saw that a function is a value. The three helpers in this lesson take a list and a function, call your function for each item, and build a result. You can pass a function you named with karya, or write one on the spot with karya (x) { ... }.

har: change every item

har(list, fn) ("every") returns a new list in which each item has been replaced by fn(item). The original list is untouched.

Expected output

Press Run to try it

[1, 4, 9, 16][RAM, SITA][1, 2, 3, 4]

chuno: keep only some items

chuno(list, fn) ("choose") keeps the items for which your function returns something truthy. It is the tidy way to say "give me only the even numbers" or "only the students who passed".

Expected output

Press Run to try it

[2, 4, 6, 8, 10][67, 40, 90]

ikattha: boil a list down to one value

ikattha(list, fn, shuru) ("together") starts with shuru, then calls fn(total_so_far, item) for every item and keeps whatever it returns. Summing is the simplest case; finding the longest word or counting matches works the same way.

You can chain the helpers: pick, then transform, then total.

Expected output

Press Run to try it

30Bill: 1000

Practice exercise

From rakho prices = [40, 150, 99, 250, 10]; keep prices above 50, add 18% GST to each with har (multiply by 1.18 and round with ganit.round), and print the list and the total. Expected: [177, 117, 295] then Total: 589.

Expected output

[177, 117, 295]
Total: 589
Open in playground
Show solution
solution.altf
rakho prices = [40, 150, 99, 250, 10];
rakho mehenge = chuno(prices, karya (p) { lautao p > 50; });
rakho gst = har(mehenge, karya (p) { lautao ganit.round(p * 1.18); });
bol(gst);
bol("Total:", ikattha(gst, karya (a, b) { lautao a + b; }, 0));