Page 5: Keeping Items from a List

Unit 2, Lab 3, Page 5

On this page, you will use predicates with the keep block to keep items in a list that have specific characteristics.

As you know, predicates can be used with conditionals to decide when to do something; they can also be used with keep to decide which things to keep. The keep items 'predicate input slot' from 'list input slot' block takes a list and a predicate as input, and it reports a new list keeping only the items from the input list that make the condition described by the predicate true.

For example, the following expression will find words from the words list whose first letter is v. The blank input slot is where each item of the list goes to decide if it will be kept.
keep items  ((letter(1) of ( )) = (v)) from (words list)

: String and Index

  • A string is an ordered sequence of characters.
  • You’ve already learned the word index for the position of an element in a list. The same word is used for the position of a character in a string (for example, a letter in a word). So the first input to letter is the index.

You write the predicate that does the checking, and keep applies the predicate to each item in the input list and then reports the list of items that make your predicate true.

Note that the blank input slot in the predicate is required; this is where each item from the list goes as it is checked by the predicate.

The letter block in the palette looks like letter (1) of (world). You have to delete the “world” so that there is a blank slot where you need it to be.

  1. Click here to load this file. Then save it to your Snap! account.

    This project contains two example keep expressions and an initialize list procedure (you can look inside it to see what it does).

  2. Talk with Your Partner Experiment with these examples of keep. Discuss and then explain in writing what these expressions are doing.
    keep items  ((length of ( )) = (5)) from {apple, banana, orange, grape, kiwi, mango, watermelon} reporting {apple, grape, mango}
    keep items  (not(is () a (number)?)) from {5, :), six, 7, elephant, 3} reporting {5,7,3}

The first example keeps inputs of a certain length; every word in the list is asked whether its length is 5, and only those with five letters are reported. The second example keeps inputs that are not numbers; every item in this list is asked “Is this item not a number?” and only the elements that are not numbers are reported.

There are two length blocks in Snap!. One (length ()) is designed for strings, and the other (length ()) is designed for lists.

  1. If you don’t see a list of words on the stage, run initialize list. Then use keep to answer these questions:

    1. How many 12-letter words are in words list?
    2. How many 15-letter words are in words list?
    3. How many 17-letter words are in words list?