Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub enum Product {
- Number(i32),
- Product(Box<Product>, Box<Product>),
- }
- impl Product {
- pub fn sign(&self) -> i32 {
- match self {
- Product::Number(n) => n.signum(),
- Product::Product(p1, p2) => {
- let s1 = p1.sign();
- if s1 == 1 {
- p2.sign()
- } else {
- -p2.sign()
- }
- }
- }
- }
- }
- struct ChainedProduct {
- value: i32,
- next: Option<Box<ChainedProduct>>,
- }
- impl ChainedProduct {
- pub fn new(values: &[i32]) -> ChainedProduct {
- assert!(!values.is_empty());
- ChainedProduct {
- value: values[0],
- next: if values.len() > 1 {
- Some(Box::new(ChainedProduct::new(&values[1..])))
- } else {
- None
- },
- }
- }
- pub fn sign(self) -> i32 {
- if self.next.is_none() {
- return self.value.signum();
- }
- if self.value.signum() == 1 {
- self.next.unwrap().sign()
- } else {
- -self.next.unwrap().sign()
- }
- }
- }
- fn main() {
- let p = Product::new(-1, Product::new(2, Product::new(-3, Product::new(1, Product::new(-2, Product::new(-3, -4))))));
- println!("{}", p.sign());
- let cp = ChainedProduct::new(&[-1, 2, -3, 1, -2, -3, -4]);
- println!("{}", cp.sign());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement