Skip to content

Commit

Permalink
Fix and extend ControlFlow traverse_inorder example
Browse files Browse the repository at this point in the history
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
  • Loading branch information
yanok committed Oct 24, 2021
1 parent 508fada commit f3795e2
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions library/core/src/ops/control_flow.rs
Expand Up @@ -24,7 +24,7 @@ use crate::{convert, ops};
/// ```
///
/// A basic tree traversal:
/// ```no_run
/// ```
/// use std::ops::ControlFlow;
///
/// pub struct TreeNode<T> {
Expand All @@ -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)?;
/// }
Expand All @@ -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)]
Expand Down

0 comments on commit f3795e2

Please sign in to comment.