#include "list_ops.h" #include #include list_t *new_list(size_t length, list_element_t elements[]) { list_t *list = malloc(sizeof(list_t) + length * sizeof(list_element_t)); list->length = length; for (size_t i = 0; i < length; i++) { list->elements[i] = elements[i]; } return list; } list_t *append_list(list_t *list1, list_t *list2) { size_t new_length = list1->length + list2->length; list_t *new_list = malloc(sizeof(list_t) + new_length * sizeof(list_element_t)); new_list->length = new_length; for (size_t i = 0; i < list1->length; i++) { new_list->elements[i] = list1->elements[i]; } for (size_t i = 0; i < list2->length; i++) { new_list->elements[list1->length + i] = list2->elements[i]; } return new_list; } list_t *filter_list(list_t *list, bool (*filter)(list_element_t)) { list_t *temp_list = malloc(sizeof(list_t) + list->length * sizeof(list_element_t)); temp_list->length = 0; for (size_t i = 0; i < list->length; i++) { if (filter(list->elements[i])) { temp_list->elements[temp_list->length++] = list->elements[i]; } } list_t *filtered_list = new_list(temp_list->length, temp_list->elements); free(temp_list); return filtered_list; } size_t length_list(list_t *list) { return list->length; } list_t *map_list(list_t *list, list_element_t (*map)(list_element_t)) { list_t *mapped_list = malloc(sizeof(list_t) + list->length * sizeof(list_element_t)); mapped_list->length = list->length; for (size_t i = 0; i < list->length; i++) { mapped_list->elements[i] = map(list->elements[i]); } return mapped_list; } list_element_t foldl_list(list_t *list, list_element_t initial, list_element_t (*foldl)(list_element_t, list_element_t)) { list_element_t accumulator = initial; for (size_t i = 0; i < list->length; i++) { accumulator = foldl(list->elements[i], accumulator); } return accumulator; } list_element_t foldr_list(list_t *list, list_element_t initial, list_element_t (*foldr)(list_element_t, list_element_t)) { list_element_t accumulator = initial; for (int i = list->length - 1; i >= 0; i--) { accumulator = foldr(list->elements[i], accumulator); } return accumulator; } list_t *reverse_list(list_t *list) { list_t *reversed_list = malloc(sizeof(list_t) + list->length * sizeof(list_element_t)); reversed_list->length = list->length; for (size_t i = 0; i < list->length; i++) { reversed_list->elements[i] = list->elements[list->length - 1 - i]; } return reversed_list; } void delete_list(list_t *list) { free(list); }