Fix and extend ControlFlow `traverse_inorder` example

1. The existing example compiles on its own, but any usage fails
   to be monomorphised and so doesn't compile. Fix that by using
   a mutable reference as an input argument.
2. Added an example usage of `traverse_inorder` showing how we
   can terminate the traversal early.

Fixes #90063
This commit is contained in:
Ilya Yanok 2021-10-23 11:40:46 +02:00
parent 508fadab16
commit f3795e27c1
1 changed files with 16 additions and 14 deletions

View File

@ -24,7 +24,7 @@ use crate::{convert, ops};
/// ```
///
/// A basic tree traversal:
/// ```no_run
/// ```
/// use std::ops::ControlFlow;
///
/// pub struct TreeNode<T> {
@ -34,7 +34,7 @@ use crate::{convert, ops};
/// }
///
/// impl<T> TreeNode<T> {
/// pub fn traverse_inorder<B>(&self, f: &impl Fn(&T) -> ControlFlow<B>) -> ControlFlow<B> {
/// pub fn traverse_inorder<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
/// if let Some(left) = &self.left {
/// left.traverse_inorder(f)?;
/// }
@ -44,30 +44,32 @@ use crate::{convert, ops};
/// }
/// ControlFlow::Continue(())
/// }
/// fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
/// Some(Box::new(Self { value, left: None, right: None }))
/// }
/// }
///
/// let node = TreeNode {
/// value: 0,
/// left: Some(Box::new(TreeNode {
/// value: 1,
/// left: None,
/// right: None
/// })),
/// left: TreeNode::leaf(1),
/// right: Some(Box::new(TreeNode {
/// value: 2,
/// left: None,
/// right: None
/// value: -1,
/// left: TreeNode::leaf(5),
/// right: TreeNode::leaf(2),
/// }))
/// };
/// let mut sum = 0;
///
/// node.traverse_inorder(& |val| {
/// println!("{}", val);
/// if *val <= 0 {
/// ControlFlow::Break(())
/// let res = node.traverse_inorder(&mut |val| {
/// if *val < 0 {
/// ControlFlow::Break(*val)
/// } else {
/// sum += *val;
/// ControlFlow::Continue(())
/// }
/// });
/// assert_eq!(res, ControlFlow::Break(-1));
/// assert_eq!(sum, 6);
/// ```
#[stable(feature = "control_flow_enum_type", since = "1.55.0")]
#[derive(Debug, Clone, Copy, PartialEq)]