Skip to content

Commit

Permalink
Rollup merge of #90196 - yanok:master, r=scottmcm
Browse files Browse the repository at this point in the history
Fix and extent ControlFlow `traverse_inorder` example

Fix and extent 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 Fn trait instead of FnMut.
2. Added an example usage of `traverse_inorder` showing how we can terminate the traversal early.

Fixes #90063
  • Loading branch information
matthiaskrgr committed Oct 25, 2021
2 parents 2f67647 + f3795e2 commit 14931b9
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions library/core/src/ops/control_flow.rs
Original file line number Diff line number Diff line change
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,17 +34,42 @@ use crate::{convert, ops};
/// }
///
/// impl<T> TreeNode<T> {
/// pub fn traverse_inorder<B>(&self, mut f: impl FnMut(&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(&mut f)?;
/// left.traverse_inorder(f)?;
/// }
/// f(&self.value)?;
/// if let Some(right) = &self.right {
/// right.traverse_inorder(&mut f)?;
/// right.traverse_inorder(f)?;
/// }
/// 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: TreeNode::leaf(1),
/// right: Some(Box::new(TreeNode {
/// value: -1,
/// left: TreeNode::leaf(5),
/// right: TreeNode::leaf(2),
/// }))
/// };
/// let mut sum = 0;
///
/// 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 14931b9

Please sign in to comment.