Point-in-Polygon Test
Tutorial Video
Text description (accessibility)
This video demonstrates the "Point-in-Polygon Test" functional Rust example. Difficulty level: Intermediate. Key concepts covered: Functional Programming. Determining whether a point lies inside a polygon is fundamental to GIS applications, game collision detection, map interfaces (is this GPS coordinate inside this region?), and computational geometry. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Determining whether a point lies inside a polygon is fundamental to GIS applications, game collision detection, map interfaces (is this GPS coordinate inside this region?), and computational geometry. The ray casting algorithm casts a horizontal ray from the query point rightward and counts crossings with polygon edges — an odd count means inside, even means outside. The winding number algorithm counts how many times the polygon winds around the point, handling non-convex and self-intersecting polygons correctly. These tests appear in every GIS library, game physics engine, and graphics renderer.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Mutation | inside = !inside (bool flip) | inside := not !inside |
| Edge iteration | for i in 0..n with j = i | for loop or fold_left |
| Previous vertex | Separate j variable | Same or pair in fold state |
| Float comparison | != for f64 (works here) | <> for float |
| Winding number | Separate function | Same approach |
| Batch queries | fn contains_batch | List.map (point_in_polygon poly) |
OCaml Approach
OCaml implements point-in-polygon with a List.fold_left over edge pairs or a for loop with Array. The condition is identical floating-point arithmetic. OCaml's ref for the mutable inside flag: let inside = ref false in ... inside := not !inside. The functional version threads the crossing count and previous vertex through fold. OCaml's List.filteri can pre-filter edges that could possibly cross the query point's y-coordinate for batch optimization.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Point In Polygon
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
point_on_edge test and handle the "on boundary" case by returning an enum Inside/Outside/OnBoundary.