Mercurial > lbo > hg > memoize
changeset 68:bf87b6014441
Add patterns example
author | Josh <josh.ja.butt@gmail.com> |
---|---|
date | Sat, 01 Jan 2022 18:18:17 +1000 |
parents | 7cef162c3281 |
children | 0ada62444b37 |
files | examples/patterns.rs |
diffstat | 1 files changed, 25 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/patterns.rs Sat Jan 01 18:18:17 2022 +1000 @@ -0,0 +1,25 @@ +use memoize::memoize; + +// Patterns in memoized function arguments must be bound by name. +#[memoize] +fn manhattan_distance(_p1 @ (x1, y1): (i32, i32), _p2 @ (x2, y2): (i32, i32)) -> i32 { + (x1 - x2).abs() + (y1 - y2).abs() +} + +#[derive(Clone, PartialEq, Eq, Hash)] +enum OnlyOne { + Value(i32), +} + +#[memoize] +fn get_value(_enum @ OnlyOne::Value(value): OnlyOne) -> i32 { + value +} + +fn main() { + // `manhattan_distance` is only called once here. + assert_eq!(manhattan_distance((1, 1), (1, 3)), 2); + + // Same with `get_value`. + assert_eq!(!get_value(OnlyOne::Value(0)), 0); +}