Lists
You need to learn how to work with linked lists. It's the number one data structure that you wan to represent a sequence of data. First try the following in a terminal, you need to understand how lists are constructed and decomposed uing pattern matching.
Open up new module and implement the following list processing functions (again we will have to call them something not that obvious in order not to create a conflict with the built-in functions):
Take and drop
Implement a function tak/1 (a function called tak taking one argument) that returns the first element of a list.
Implement a function drp/1 that returns a list where the first element has been removed.
What should the above functions return if you call them with a emty list [ ]
? If you have not done anything a call will return an error. This i perfectly fine but let's change the code so it either returns {:ok, res}
or :no
if we provide anything but a list with at least one element.
length and sum
These are some simple functions that you should implement. They will all use recursion so first try to formulate in words what the definition should look like, then implement it.
len(l)
: return the number of elements in the list lsum(l)
: return the sum of all elements in the list l, assume thatall elements are integers
some more thinking
These functions take some more thinking. You should return a list as a result of evaluating the function.
duplicate(l)
: return a list where all elements are duplicatedadd(x, l)
: add the element x to the list if it is not in the listremove(x, l)
: remove all occurrences of x in lunique(l)
: return a list of unique elements in the list l
append two lists
Implement a function that appends two list into one list.
reverse a list
One interesting problem to look at is how to reverse a list. The naive way to do it is quite straight forward. We do it recursively by removing the first element of the list, reversing the rest and then appending the reversed list to a list containing only the first element.
A smarter way to do it, is to use an accumulator and add the first element to this accumulator. When we have added all elements in the lists the accumulated list is the reversed list.
Ok, so what is so smart by doing this? This is your assignment, you should do some performance analysis of these two functions and describe what is happening. To have some data lead you in the right direction and to back up your findings you should start by doing some performance measurements.
We have here used some library functions and higher order programming that you might not have seen so far but don't worry, you will get use to it.
Last updated