I try to be gentle ;-) So, the main thing in a functional approach is to think in terms of: what is a contribution? What should be output? There is nothing like comparing the ith element with the i + 1th element. There should always be a goal that will lead to data transformation. Even the Mazen Harake example does this. In this example, there is a function that returns only elements followed by the same value, i.e. Filters this list. As a rule, there are different ways, like a similar thing, which depends on the goal. A list is a basic functional structure, and you can do amazing things with it, as Lisp shows us, but you must remember that it is not an array.
Every time you need access to the ith element, it indicates that you are using the wrong data structure. You can create various data structures by creating lists and tuples in Erlang that can serve your purposes better. Therefore, when you are faced with the problem of comparing the i-th with the i + 1-m element, you should stop and think. What is this goal? Do you need to do some kind of stream data conversion like Mazen Harake or do you need random access? If the latter you should use a different data structure ( array , for example). Even then you have to think about your tasks. If you will mostly read and almost never write, you can use list_to_tuple(L)
and then read with element/2
. When you need to write sometimes, you will begin to think about dividing it into several tuples, and as your attitude to writing grows, you will get an implementation of array
.
That way, you can use lists:nth/2
if you do this only once or several times, but on a short list, and you are not a producer like me. You can improve it by using [X1,X2|_] = lists:nthtail(I-1, L)
( L = lists:nthtail(0,L)
works as expected). If you come across large lists, and you want to name it many times, you need to reconsider your approach.
PS: There are many other fascinating data structures besides lists and trees. Lightning, for example.
source share