An introduction to methods that let us construct new lists

The simplest constructors are those that you have already seen: the methods list.empty and list.with(_) in standard, and the methods list.empty, list(_), list(_,_), list(_,_,_), etc. in beginningStudent. These methods create lists containing the given element (or elements) in the given order.

More interesting are methods on lists that construct other lists. One that should look familiar is the concatenation operator ++, because it works on lists in the same way that it works on strings.

Notice that snacks is a new list, quite separate from cheeses and fruits, although its initial contents comes from cheeses and fruits.

Here are some other methods on lists that construct new lists:

reversed -> List⟦ElementType⟧
// returns a List containing my values, but in the reverse order.

sorted -> List⟦ElementType⟧
// returns a List containing my values, but in an order determined by
// the ≤ method on the elements.

sortedBy(sortBlock:Function2⟦ElementType, ElementType, Number⟧) -> List⟦ElementType⟧
// returns a List containing my values, but in an order determined by
// the sortBlock argument.  The sortBlock is a piece of code that determines what it
// means for one element to be less than or greater than another.
// The sortBlock must return 0 when two elements are equal, -1
// if the first is "less than" the second, and +1 if the first is "greater than" the second.

sorted is simple to use:

Notice that generating a sorted list of cheeses doesn’t change the original list; sorted is a constructor, not a mutator method. Don’t confuse it with sort!

The sorted method won’t work for the next example, in which the list elements are themselves lists. That’s because there is no ordering method on list. We can solve this problem by using sortedBy(sortBlock); the sortBlock that we use here compares the second elements of the component lists, so the result is sorted by the cheese, not the fruit. Experiment! Can you sort in the reverse order, or by the fruit?

Once again, notice that snacks.sortedBy does not change snacks.