In-Class exercise: Elm 2

To avoid having to install Elm on your machine, we'll be using Ellie, a simple Elm IDE in the cloud.

The goal for this exercise is to earn to use Elm commands. In particular, we'll be modifying the People application so that it generates random IDs (rather than incrementing a nextId).

  1. Open the People application in https://ellie-app.com/fMVYtQnTL4ma1. Verify that it displays the People application. (Note that you'll need to accept the Terms of Service.)
  2. Import the Random package. Then, compile and fix things until there are no errors.

    Hint: To add a package, click on the packages icon in the left, search for the package, and then click Install.

  3. Switch the application from using Browser.sandbox to Browser.element. Then, compile and fix things until there are no errors.

    Hint: You'll need to add a subscriptions field initialized to a function that takes a Model and returns Sub.none

    Hint: You'll need to modify the init method.

    Hint: You'll need to modify the update method.

  4. Create a new message CreatePersonWithId that takes an ID number and creates a person with that ID (copy code from the CreatePerson message). Then, compile and fix things until there are no errors.
  5. Modify the code for CreatePerson to no longer modify the people of the model, but instead to return a command that generates a a CreatePersonWithId message initialized with model.nextId. Then, compile and fix things until there are no errors.

    Hint: Random.constant is a Random generator that will generate the same number each time.

  6. Add a call to Debug.log that prints out the people in the view function. Test the application by adding some people and checking in the Ellie Logs panel that the IDs being generated are still consecutive.

    Hint: The debugging logger returns a value so you'll normally need to use it in a let clause:

    let
      _ = Debug.log "label" value
    in
    expression
    
  7. Remove nextId from the model. Then, compile and fix things until there are no errors.
  8. Challenge: modify the init method so that rather than hardcoding the IDs of the two starting people, it uses the random number generator to create the IDs.

    Hint: consider using Cmd.batch.