Skip to content

Instantly share code, notes, and snippets.

@JonNorman
Last active October 29, 2018 13:23
Show Gist options
  • Save JonNorman/8956579cf7892c31ea8203c30c900b30 to your computer and use it in GitHub Desktop.
Save JonNorman/8956579cf7892c31ea8203c30c900b30 to your computer and use it in GitHub Desktop.
Exercises to go through in class, introducing the `Option` type.

Exercises:

  1. Write a function called parsePhoneNumber that takes as an argument phoneNumber: String and returns a Option[String] representing a phone number. Why might we want to use String here and not Int?

  2. Write a better max function that returns an Option[Int] given an argument of type List[Int]. How would you write this for a list of String? How about a List[Boolean]? Would the implementations differ in any meaninful way?

  3. Define a case class User that represent a user in our imaginary app. A User should have an id a name and an optional email.

  4. Create a list of Users - call it users - that contains 2 Users. Let's pretend that this is some database of users for our app.

  5. Write a function findUser(id: String) that searches for a User in our list and returns an Option[User], where it returns None if our users list doesn't contain a User with that id.

  6. Write a function getEmailDomain(id: String) that returns an Option[String]. This function should look up the user in our users list and, if there is an email defined, extract the domain (the part after the '@' in the email) and return that as a Some, otherwise it should return a None. What is the return type of this? You may end up with an Option[Option[String]] - why is this? Let's discuss.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment