Does erlang have a hidden rownum in the list?

This is an example of my current code:

DataSet = [1,2,3,4,5,6,7,8,9]. Sequence = [3,4,5,6]. ReducedDataSet = lists:foldl( fun(SeqNumber, Output) -> Row = lists:nth(SeqNumber, DataSet), [Row|Output] end, [], Sequence ). 

The ReducedDataSet ends as [6,5,4,3], and if I change it to lists: foldr, the ReducedDataSet will be [3,4,5,6].

I did not expect this, as if it was absorbed from left to right, the third value is 3 and should continue to 6, but when absorbed from right to left, the 3rd value will be 7 and go to 4.

Does this mean that my list has a hidden line number, and foldl and foldr differ only in the sort order of the final list?

+5
source share
2 answers

TL DR

No, the Erlang list does not have a hidden index or "line number".

Discussion

It may be useful to study the nature of list operations a bit more in the context of functional lists of the variety of "lists are a bunch of conses."

I wrote an explanation of the folds that may be useful to you: Explanation of lists: collapse function

Keep in mind that function lists only have pointers that go one way. That is, they are separate lists. There is no concept of "rownum" or "index" as it would be in an array of C styles. Each call to lists:nth/2 actually moves the list to the nth item before returning that item.

We could write lists:nth/2 like this if we want a version that fails on bad input (and, looking up, it turns out that it is written almost the same way) :

 nth(1, [Element | _]) -> Element; nth(N, [_ | Rest]) when N > 1 -> lists:nth(N - 1, Rest). 

(As a note, pay attention to non-embedding funs, requiring you to write multi-line definitions as function arguments ...)

+4
source

I think this is a more general fold question.

In general, a fold does the following: (new_element, acc) -> new_acc

If the operation new_element ° acc is commutative (e.g. sum ), foldl and foldr are the same.

If the operation is "append", there is a difference between adding an item left or right.

[3] ° 4 -> [3, 4] VS 4 ° [3] -> [4, 3]

I never remember that there is foldl and foldr , but I think left / right refers to the position of the battery ( [3] ° 4 is foldl with this definition)

+4
source

Source: https://habr.com/ru/post/1271717/


All Articles