10.2.2.1 adding elements to a list

Source: Internet
Author: User

10.2.2.1 adding elements to a list

So far, we've seen how to append elements to the previous (functional) list, and what if we want to append elements to the end of the list? This requirement sounds reasonable, so we try to implement it. Listing 10.10 shows the difference in performance between the front of the list and the insertion of Na?ve attempts later.

Listing 10.10 Adding elements to the list (F # Interactive)

> Let prepend el list = el::list;; [1]

Val prepend: ' A list, ' a ' alist

> Let rec append el list = [2]

Match Listwith

| []->[el] <--append to Empty list

| X::xs->x::(append el xs) <--recursively append to the remainder

Val Append: ' A list, ' a list

> #time;; [3]

> Let L = [1.. 30000];;

Val L:int List

> For i = 1 to + do ignore (prepend 1l);; |

real:00:00:00.000, cpu:00:00:00.000 |

| Additional performance is slower

> For i = 1 to + do ignore (append 1l);; |

real:00:00:00.434, cpu:00:00:00.421 |

The implementation of prepend is very simple [1], because a new list cell can be constructed directly using the cons operator (::), while appending the element to the end of the list requires writing the recursive function [2], following the usual recursive list processing pattern, one branch handling the empty list, and the other handling the cons cell.

Next, we enter a very useful F # Interactive command, #time, to open the timer (timing). In this mode, F # automatically outputs the time it takes to execute the commands we enter. You can see that for large lists, appending elements at the end is much slower. We run 100 times in the For loop, and the time required to append in the front is zero, but appending the elements later takes a considerable amount of time. Any "simple" operation, it is only half a second to be afraid, the iteration 100 times is worth paying attention to.

Our append function is not a tail recursion, but it is not a problem here. Tail recursion avoids stack overflow, but has a slight impact on performance. The problem is that a functional list is not appropriate for the action we are trying to perform.

Figure 10.5 shows why this operation cannot be implemented effectively for a functional list, but it is easy to append elements in front of them. Because the list is an immutable data structure, we can create a unit and point to the original list. Immutability Guarantee No one can change the original list, and the content of the "new" list is changed behind our backs. In contrast, appending elements later requires that the last element be changed. Previously, the last element "knew" it itself at the end, and we needed to have a new element behind it. The list is immutable, so you cannot change the information that is stored in the last element. Instead, you must clone the last element, so that the previous element is cloned (so that it knows, followed by the last element of the clone), and so on.

Figure 10.5 Appends the elements above, we create a new cons cell and a reference to the original list, and append the elements later, we need to traverse and clone the entire list.

Of course, there are different data structures, each of which has different operations that can be performed efficiently. There is always a tradeoff, which is why it is important to choose the right data structure for different problems.

Complexity of the algorithm

Computer scientists use very precise mathematical terminology to discuss the complexity of algorithms, but the concepts behind these terms are even more important, even when we are informally using them. In general, the complexity of the operation tells us that the algorithm requires the number of "raw" steps, depending on the size of the input. It does not predict the number of steps and is only related to the size of the input.

Let's examine the previous example. Appending an element to the front of the list always involves a separate step: Create a new list cons cell. In formal notation, write O (1), which means that the number of steps is constant, regardless of the size of the list. Add elements before the list with 1 million elements, just like adding elements in front of a list of only one element!

Appending elements to the back of the list is tricky. At the beginning, if there are n elements in the list, we need to process and repeat n cons cells. This can be written as O (N), which indicates that the number of steps is roughly proportional to the size of the list: adding elements after a list of 1000 elements is about twice times the element added after the list of 1000 elements.

For example, if we want to append a list of M new elements, its complexity should be multiplied by M. This means that the append in front will require O (m) step, because, 1*m = M. Using a similar principle, appending to the back will require an O (N * M) step, which may be a larger order of magnitude.

So far, we've discussed the functional list, which is the most important set in function programming. Let's take a big leap and take a look at the collections that exist in almost all imperative programming languages: humble arrays. F # is a. NET language, so it can also use a normal. NET array.

10.2.2.1 adding elements to a list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.