Lesson 6: Strings and Lists

Intermediate

This lesson covers the two most common compound data types: strings (text) and lists (ordered collections).

String primitives

PrimitiveInputsOutputDescription
concata, bstringJoin two strings
lengthstringintegerNumber of characters
to-stringanystringConvert to text
splitstring, separatorlistSplit into parts
trimstringstringRemove leading/trailing whitespace
replacestring, old, newstringReplace occurrences

Example: greeting

"Hello, " "Ada" a b concat "Hello, Ada"

List primitives

A list is an ordered collection. Elements can be any type and can be mixed. Lists are 1-indexed in Phograph (the first element is at position 1).

PrimitiveInputsOutputDescription
get-nthlist, indexelementGet element at position (1-indexed)
appendlist, elementlistAdd element to end
lengthlistintegerNumber of elements
sortlistlistSort in ascending order
empty?listbooleanTrue if list is empty
1-indexed Unlike most programming languages (which start at 0), Phograph lists are 1-indexed, following the original Prograph convention. The first element is at index 1.

Building lists

There is no list-literal node yet. To build a list, start with an empty list and append elements:

() empty list "a" list elem append "b" list elem append ("a", "b")

Walkthrough: String Processing example

Load String Processing > String Concatenation from the Example Browser.

This example concatenates "Hello, " and "Phograph!", then logs the result. It demonstrates the concat primitive.

Exercise 6.1 — Build a greeting

  1. Create a method greet (1 input, 1 output) that prepends "Hello, " to the input and appends "!".
  2. Use two concat nodes chained together.
  3. Call greet from main with "World".
  4. Result: "Hello, World!".

Exercise 6.2 — Split and count

  1. Create a constant "one,two,three,four".
  2. Use split with separator "," to get a list of words.
  3. Use length on the resulting list.
  4. Log the length. Should print 4.

Exercise 6.3 — Reverse a list (challenge)

Write a recursive method reverse (1 input, 1 output):

  1. Case 1: check if the list is empty (empty? with nextCaseOnFailure). If true, return the empty list.
  2. Case 2: get the first element (get-nth with index 1), get the rest of the list (you may need a slice or rest primitive), recursively reverse the rest, and append the first element to the result.
Hint

If a rest primitive is not available, you can use a recursive approach where you get-nth the last element, append it to a new list, and shrink the input. Alternatively, use the built-in sort as inspiration — the important thing is to practice recursion with cases.

Key Concepts