Last active
July 29, 2024 02:38
-
-
Save dcormier/3ec7f4bfd08dcd7a2bdd57192bb8826b to your computer and use it in GitHub Desktop.
Enclose a string written by a closure in opening and closing chars, or a specified number of parentheses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Encloses the string written by `enclosed` in the opening an closing | |
/// characters provided. | |
fn enclose<F>(s: &mut String, open: char, close: char, enclosed: F) | |
where | |
F: FnOnce(&mut String), | |
{ | |
s.push(open); | |
enclosed(s); | |
s.push(close); | |
} | |
/// The string written by the `enclosed` function will be enclosed in | |
/// `parens_count` pairs of parentheses. A count of `0` is allowed. | |
fn parenthesize<F>(s: &mut String, parens_count: usize, enclosed: F) | |
where | |
F: FnOnce(&mut String), | |
{ | |
match parens_count { | |
0 => { | |
enclosed(s); | |
return; | |
} | |
1 => { | |
enclose(s, '(', ')', enclosed); | |
return; | |
} | |
_ => {} | |
} | |
let mut enclosed: Box<dyn FnOnce(&mut String)> = Box::new(enclosed); | |
for _ in 0..parens_count { | |
enclosed = Box::new(|s| enclose(s, '(', ')', enclosed)); | |
} | |
enclosed(s); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment