HASKELL / CHAPTER 08

Maybe and total interfaces

Advanced

Represent an absent result without a partial list operation.

By the end of this chapter

  • Distinguish Nothing from Just
  • Define safe lookup behavior
  • Transform present data while preserving absence

The idea

Enter with algebraic patterns and polymorphic type variables understood. Maybe a represents either Nothing or Just containing a value of type a. It allows a function to describe absence explicitly without inventing a special element value. A safe first-element function can therefore accept an empty list while retaining the original element type for successful results.

Pattern matching forces the consumer to decide what absence means at its boundary. It might display a message, supply a documented default, or continue with another optional computation. fmap applies a function to a present value while preserving Nothing. Avoid replacing a meaningful distinction too early: Nothing and Just 0 can carry different information even when a later display chooses the same number for both.

Haskell example
safeFirst :: [a] -> Maybe a
safeFirst [] = Nothing
safeFirst (x:_) = Just x
main = print (fmap (+2) (safeFirst [5,9]))
Result
Just 7

safeFirst returns Just 5. fmap transforms its payload by adding two and keeps the result inside Just.

Try it yourself

Write safeLast :: [a] -> Maybe a for finite lists, covering empty input explicitly.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which result represents a present integer zero?