C: list-ops

This commit is contained in:
2021-08-23 17:32:21 +02:00
parent 7cf02bc336
commit d3002514a5
5 changed files with 342 additions and 0 deletions

51
c/list-ops/GNUmakefile Normal file
View File

@@ -0,0 +1,51 @@
# The original 'makefile' has a flaw:
# 1) it overrides CFLAGS
# 2) it does not pass extra "FLAGS" to $(CC) that could come from environment
#
# It means :
# - we need to edit 'makefile' for different builds (DEBUG, etc...), which is
# not practical at all.
# - Also, it does not allow to run all tests without editing the test source
# code.
#
# To use this makefile (GNU make only):
# "make": build with all predefined tests (without editing test source code)
# "make debugall": build with all predefined tests and debug code
# "make mem": perform memcheck with all tests enabled
# "make unit": build standalone (unit) test
# "make debug": build standalone test with debugging code
#
# Original 'makefile' targets can be used (test, memcheck, clean, ...)
.PHONY: default all mem unit debug std debugtest
default: all
# default is to build with all predefined tests
BUILD := teststall
include makefile
all: CFLAGS+=-DTESTALL
all: clean test
debugall: CFLAGS+=-DDEBUG
debugall: all
debugtest: CFLAGS+=-DDEBUG
debugtest: test
mem: CFLAGS+=-DTESTALL
mem: clean memcheck
unit: CFLAGS+=-DUNIT_TEST
unit: clean std
debug: CFLAGS+=-DUNIT_TEST -DDEBUG
debug: clean std
debugtest: CFLAGS+=-DDEBUG
debugtest: test
std: src/*.c src/*.h
$(CC) $(CFLAGS) src/*.c -o tests.out $(LIBS)

54
c/list-ops/README.md Normal file
View File

@@ -0,0 +1,54 @@
# List Ops
Implement basic list operations.
In functional languages list operations like `length`, `map`, and
`reduce` are very common. Implement a series of basic list operations,
without using existing functions.
The precise number and names of the operations to be implemented will be
track dependent to avoid conflicts with existing names, but the general
operations you will implement include:
* `append` (*given two lists, add all items in the second list to the end of the first list*);
* `concatenate` (*given a series of lists, combine all items in all lists into one flattened list*);
* `filter` (*given a predicate and a list, return the list of all items for which `predicate(item)` is True*);
* `length` (*given a list, return the total number of items within it*);
* `map` (*given a function and a list, return the list of the results of applying `function(item)` on all items*);
* `foldl` (*given a function, a list, and initial accumulator, fold (reduce) each item into the accumulator from the left using `function(accumulator, item)`*);
* `foldr` (*given a function, a list, and an initial accumulator, fold (reduce) each item into the accumulator from the right using `function(item, accumulator)`*);
* `reverse` (*given a list, return a list with all the original items, but in reversed order*);
## Getting Started
Make sure you have read the "Guides" section of the
[C track][c-track] on the Exercism site. This covers
the basic information on setting up the development environment expected
by the exercises.
## Passing the Tests
Get the first test compiling, linking and passing by following the [three
rules of test-driven development][3-tdd-rules].
The included makefile can be used to create and run the tests using the `test`
task.
make test
Create just the functions you need to satisfy any compiler errors and get the
test to fail. Then write just enough code to get the test to pass. Once you've
done that, move onto the next test.
As you progress through the tests, take the time to refactor your
implementation for readability and expressiveness and then go on to the next
test.
Try to use standard C99 facilities in preference to writing your own
low-level algorithms or facilities by hand.
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
[c-track]: https://exercism.io/my/tracks/c
[3-tdd-rules]: http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd

37
c/list-ops/makefile Normal file
View File

@@ -0,0 +1,37 @@
### If you wish to use extra libraries (math.h for instance),
### add their flags here (-lm in our case) in the "LIBS" variable.
LIBS = -lm
###
CFLAGS = -std=c99
CFLAGS += -g
CFLAGS += -Wall
CFLAGS += -Wextra
CFLAGS += -pedantic
CFLAGS += -Werror
CFLAGS += -Wmissing-declarations
CFLAGS += -DUNITY_SUPPORT_64
ASANFLAGS = -fsanitize=address
ASANFLAGS += -fno-common
ASANFLAGS += -fno-omit-frame-pointer
.PHONY: test
test: tests.out
@./tests.out
.PHONY: memcheck
memcheck: test/*.c src/*.c src/*.h
@echo Compiling $@
@$(CC) $(ASANFLAGS) $(CFLAGS) src/*.c test/vendor/unity.c test/*.c -o memcheck.out $(LIBS)
@./memcheck.out
@echo "Memory check passed"
.PHONY: clean
clean:
rm -rf *.o *.out *.out.dSYM
tests.out: test/*.c src/*.c src/*.h
@echo Compiling $@
@$(CC) $(CFLAGS) src/*.c test/vendor/unity.c test/*.c -o tests.out $(LIBS)

138
c/list-ops/src/list_ops.c Normal file
View File

@@ -0,0 +1,138 @@
#include <malloc.h>
#include <string.h>
#include <stdint.h>
#include "list_ops.h"
#define SIZE(l) ((l)->length * sizeof(list_element_t))
list_t *new_list(size_t len, list_element_t elts[])
{
list_t *list;
if (len > MAX_LIST_LENGTH ||
!(list=malloc(sizeof(list_t) + len*sizeof(list_element_t))))
return NULL;
list->length = len;
if (elts)
memcpy(list->elements, elts, len * sizeof(list_element_t));
return list;
}
list_t *append_list(list_t *l1, list_t *l2)
{
list_t *l;
size_t len=l1->length+l2->length;
if (!(l=new_list(len, NULL)))
return NULL;
memcpy(l->elements, l1->elements, l1->length * sizeof(list_element_t));
memcpy(l->elements + l1->length, l2->elements,
l2->length * sizeof(list_element_t));
l->length=len;
return l;
}
list_t *filter_list(list_t * l, bool(*f) (list_element_t))
{
size_t p1, p2;
list_t *list=new_list(l->length, NULL);
if (list) {
for (p1=0, p2=0; p1 < l->length; ++p1) {
if (f(l->elements[p1]))
list->elements[p2++]=l->elements[p1];
}
}
list->length=p2;
return list;
}
/* I don't like this function return value, and more generally using size_t
* as list length.
*/
size_t length_list(list_t *l)
{
return l? l->length: INVALID_LENGTH;
}
list_t *map_list(list_t * l, list_element_t(*map) (list_element_t))
{
size_t i;
list_t *list=new_list(l->length, NULL);
if (list) {
for (i=0; i < l->length; ++i)
list->elements[i] = map(l->elements[i]);
}
return list;
}
list_element_t foldl_list(list_t * l, list_element_t init,
list_element_t(*f) (list_element_t, list_element_t))
{
size_t i;
for (i = 0; i < l->length; ++i)
init = f(l->elements[i], init);
return init;
}
list_element_t foldr_list(list_t * l, list_element_t init,
list_element_t(*f) (list_element_t, list_element_t))
{
ptrdiff_t i;
for (i = l->length-1; i >= 0; --i)
init = f(l->elements[i], init);
return init;
}
list_t *reverse_list(list_t * l)
{
size_t i;
list_t *list=new_list(l->length, NULL);
if (list) {
for (i=0; i < l->length; ++i)
list->elements[l->length-i-1] = l->elements[i];
}
return list;
}
void delete_list(list_t * l)
{
free(l);
}
/* See GNUmakefile below for explanation
* https://github.com/braoult/exercism/blob/master/c/templates/GNUmakefile
*/
#ifdef UNIT_TEST
static void print_list(list_t *l)
{
printf("list (%lu) = ", l->length);
for (size_t i=0; i<l->length; ++i)
printf("%d ", l->elements[i]);
printf("\n");
}
int main(int ac, char **av)
{
int arg=1, i;
list_t *l1=new_list(0, NULL);
list_t *l2, *l3;
for (; arg<ac; ++arg) {
i=atoi(av[arg]);
l2 = new_list(1, (list_element_t[]){ i });
l3 = append_list(l1, l2);
delete_list(l2);
delete_list(l1);
l1=l3;
}
print_list(l1);
delete_list(l1);
}
#endif

62
c/list-ops/src/list_ops.h Normal file
View File

@@ -0,0 +1,62 @@
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <stdlib.h>
#include <stdbool.h>
typedef char list_element_t;
typedef struct {
size_t length;
list_element_t elements[];
} list_t;
#define MAX_LIST_LENGTH 1024
#define INVALID_LENGTH (size_t)-1
// constructs a new list
extern list_t *new_list(size_t length, list_element_t elements[]);
// append entries to a list and return the new list
extern list_t *append_list(list_t * list1, list_t * list2);
// filter list returning only values that satisfy the filter function
extern list_t *filter_list(list_t * list, bool(*filter) (list_element_t));
// returns the length of the list
extern size_t length_list(list_t * list);
// return a list of elements whose values equal the list value transformed by
// the mapping function
extern list_t *map_list(list_t * list, list_element_t(*map) (list_element_t));
// folds (reduces) the given list from the left with a function
extern list_element_t foldl_list(list_t * list, list_element_t initial,
list_element_t(*foldl) (list_element_t,
list_element_t));
// folds (reduces) the given list from the right with a function
extern list_element_t foldr_list(list_t * list, list_element_t initial,
list_element_t(*foldr) (list_element_t,
list_element_t));
// reverse the elements of the list
extern list_t *reverse_list(list_t * list);
// destroy the entire list
// list will be a dangling pointer after calling this method on it
extern void delete_list(list_t * list);
/* See GNUmakefile below for explanation
* https://github.com/braoult/exercism/blob/master/c/templates/GNUmakefile
*/
#if defined UNIT_TEST || defined DEBUG
#include <stdio.h>
#include <stdlib.h>
#endif
#ifdef TESTALL
#undef TEST_IGNORE
#define TEST_IGNORE() {}
#endif
#endif