CSC 347 - Concepts of Programming Languages

Option Type

Instructor: Stefan Mitsch

Reporting Missing Data

  1. def reduce[X](xs: List[X], f: (X,X)=>X) : X = xs match {
  2. case Nil => ???
  3. case head :: Nil => head
  4. case head :: tail => f(head, reduce(tail))
  5. } ensuring {
  6. case result => ???
  7. }
  • case Nil => null: contract and clients have to distinguish between null and a result
  • case Nil => throw IllegalArgumentException("Unable to reduce empty list"): how to write exception contract?

Learning Objectives

How to represent missing results?

  • Understand option type

Option Type

  • Principled approach to missing data
  • Option[T] resembles List[T] with length 1
    • None represents absence of data
    • Some represents presence
  • Example expressions of type Option[Int]: None, Some(5)

Absence of Data

Programming with null

  1. def getDirs1 (dirName : String) : List[java.io.File] =
  2. val dir = new java.io.File (dirName)
  3. val xs = dir.listFiles
  4. if xs == null
  5. then null
  6. else xs.toList.filter (_.isDirectory)

Programming with optionals

  1. def getDirs2 (dirName : String) : Option[List[java.io.File]] =
  2. val dir = new java.io.File (dirName)
  3. val xs = dir.listFiles
  4. if xs == null
  5. then None
  6. else Some(xs.toList.filter (_.isDirectory))

Absence of Data: Clients

With null

  1. def printNumTemp1 () =
  2. var result : List[java.io.File] = Nil
  3. var found = false
  4. for s <- List("/temp", "/tmp"); if !found do
  5. result = getDirs1(s)
  6. found = (result != null)
  7. if found
  8. then println(result.length)
  9. else println("No Temporary Directory.")

With option pattern matching

  1. def printNumTemp2 () =
  2. getDirs2("/temp") orElse getDirs2("/tmp") match
  3. case None => println("No Temporary Directory.")
  4. case Some(result) => println(result.length)
  • null: no compiler support to check for presence of null-checking, cannot have methods
  • Map, fold, filter all work on Option

Option vs. null

  • An option is a type that may have something or nothing
  • Scala has many values that represent nothing
    • None: empty option
    • Nil: empty list
    • null: reference to nothing
  • Unit is not an option type
    • Unit always has nothing
    • Unit nothing is ()

Nil vs. null

Scala

  1. def sum (xs : List[Int]) : Int = xs match
  2. case Nil => 0
  3. case y::ys => y + sum(ys)
  • Nil: empty list
  • null: empty reference

Java

  1. int sum (Node<Integer> xs)
  2. if (xs == null) return 0;
  3. else return xs.item + sum(xs.next);
  • null used to represent emptiness

Nullable Types

  • In Scala, we often pretend null does not exist
  • Recent languages identify None and null
  • Swift
  • Kotlin
  • These languages distinguish nullable and non-nullable types

Nullable Types

Kotlin nullable versus non-nullable types

  • T? in Kotlin resembles Option[T] in Scala
  • null is used for None
  • Types without ? do not allow null
  1. var a: String = "abc"
  2. a = null /* compilation error */
  3. a.length /* always safe */
  4. var b: String? = "abc"
  5. b = null /* ok */
  6. b.length /* compiler error */
  7. b!!.length /* may give Null Pointer Exception */
  8. b?.length /* Safe call */
  9. if (b != null) b.length else null /* expanded */
  10. b?.length ?: -1 /* Elvis operator */
  11. val t = b?.length; if (t != null) t else -1 /* expanded */

Java Optional

Map and FlatMap on Option

  1. def safeDivide (n:Int,m:Int) : Option[Int] =
  2. if m == 0 then None
  3. else Some (n/m)
  4. // .lift(i) safely accesses element at index i
  5. // in bounds: Some(element)
  6. // out of bounds: None replaces IndexOutOfBoundsException
  7. val a : Option[Int] = List(11,21,31).lift(2)
  8. a.map(safeDivide(_,2)) // val res10: Option[Option[Int]] = Some(Some(15))
  9. a.flatMap(safeDivide(_,2)) // val res11: Option[Int] = Some(15)

Summary

  • Option types represent absence of data
  • Can be processed like lists
  • Enable expressing alternative computation attempts concisely