A
A
Amir Kamolov2019-03-09 03:14:57
C++ / C#
Amir Kamolov, 2019-03-09 03:14:57

How to implement the map function?

Please help me understand the map function. What is she like? How to implement it and with what it is eaten in si?
l=[a_1,..,a_n]is some list of elements of type T, and f:T→T, then:
map(f,l)↦[f(a_1 ),..,f(a_n )]
It is not clear what it does and how to implement it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2019-03-09
@jcmvbkbc

l=[a_1,..,a_n] is some list of elements of type T, and f:T→T, then:
map(f,l)↦[f(a_1 ),..,f(a_n )
] it does and how to implement it.

Why is it not clear what he is doing? You wrote it yourself: applies the function f to each element of the input list.
How to implement it depends on the representation of the list, on how strictly you want to deal with types, and on how much you want to follow the standard.
For example, you can do this:
#include <stddef.h>

struct list {
    struct list *next;
};

struct list *map(void f(struct list *p), struct list *l)
{
    struct list *i;
    for (i = l; i != NULL; i = i->next)
        f(i);
    return l;
}

struct list_int {
    struct list list;
    int i;
};

void process_int(struct list *l)
{
    struct list_int *p = (struct list_int *)l;
    ++p->i;
}

int main()
{
    struct list_int l[] = {
        [0] = {
            .list.next = &l[1].list,
            .i = 1,
        },
        [1] = {
            .i = 2,
        },
    };
    map(process_int, &l[0].list);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question