Sorting Contacts by Name
There's hardly anything you have to do on this page, but that's the point — to see how easy data abstraction makes this problem.
- Read through all the blocks you wrote on the previous page, and write down a list of all the ones that assume that the list you're sorting has words or numbers, rather than Contacts (the abstract data type from Lab 1), as items.
- Compare your ideas with another group.
- Edit your
min
block so that instead of comparing text or numeric values, it compares two Contacts, using the block.
- Now try
. Debug it if necessary. Make sure the contacts are sorted by last name (family name, if you did the TIF on page 2 of Lab 1).
- Add a "sort by name" button to your contact list app. It should replace contact list with a sorted version of itself.
- It's a shame that, now that your
sort
block sorts contacts, it doesn't work for numbers any more. Make a
block. You should be able to sort numbers with
.
- The block's second input must have a type of Predicate (not Boolean). That puts the gray ring around the input slot, so that the input is the function itself, not the result of calling the function. (You'll find Predicate in the same type-choosing window in which you can declare an input to be Number or List type.)
- Pass the input predicate down to
min
, also as an input of type Predicate.
- To use the predicate inside
min
, do this:
where a and b are the two values you want to compare. To get the "with inputs" part of the call
block, you have to click the right arrowhead at the very end of the block (twice, since you want two input slots).
- Make sure you can sort both lists of numbers and lists of contacts by using appropriate predicates as the second input to
sort
.
- Use your block to sort a list of numbers from largest to smallest.
- What would happen if you used
≤
instead of <
in your comparison function? To see the effect, set up a contact list with several entries with the same name but different phone numbers or addresses.