Lesson 12 of 15
Option Type
The Option Type
OCaml uses option to represent values that might be absent — no null pointers!
type 'a option = None | Some of 'a
A value is either Some x (present) or None (absent).
Pattern Matching on Options
let describe opt =
match opt with
| None -> "nothing"
| Some x -> "got: " ^ string_of_int x
Safe Operations
Options are perfect for operations that might fail. You can use match to safely extract values:
let get_or_default opt d =
match opt with
| None -> d
| Some x -> x
Your Task
Write a function find_positive that takes a list and returns the first positive number as a string, or "none" if no positive number exists. Use a helper show_option to convert the result.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.