Writing your own map, reduce, compactMap and more Higher-Order functions

Sudhanshu Srivastava
2 min readJun 20, 2021

--

Photo by Artem Kniaz on Unsplash

Higher-Order functions; If you have some experience working in swift, you might have used it at several places in your code. A function that takes one or more function as argument is called Higher-Order function.

But here, what I am more interested in explaining is how to write your own Higher-Order function. ( It is hot question for many companies too, so stay tuned ). What I have seen in my experience that this question is put in such a way that it seems complicated when asked, which is not that tricky actually.

Let’s start with this question and answer it;

What is an Higher-Order function?
This you already know if you have reached here.

The above question has a follow-up question too

Write your own map function.

To answer this one you must know what map(_:) actually does.

Map

As Apple Documentation says

Returns an array containing the results of mapping the given closure over the sequence’s elements.

So, we need to pass an operation/function which will be applied on each element of the given Sequence to another function ( i.e. myMap(_ :) our higher-order function) which will return final Sequence with updated values.

Here operation is a “function” that’ll be applied to every element of the given Sequence (simply Array to understand).

Reduce

CompactMap

Filter

Thanks for reading.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudhanshu Srivastava
Sudhanshu Srivastava

Written by Sudhanshu Srivastava

I write about what I learn. Swift, Kotlin, Flutter, Social and Life.

No responses yet

Write a response