I found a code fragment that must use double if, which is very strange for me.
if if let Some(mut x)=heap.peek_mut(){
suppose_it_returns_a_boolean(x)
} else {
// some other logic
break
} {
heap.pop();
}
In short, I want to either modify or pop an item from a heap at some condition. when I tried pop it, an error occurs:
if let Some(mut x)=heap.peek_mut(){
if suppose_it_returns_a_boolean(x) {
heap.pop(); // boom, heap is mutable borrowed in `heap.peek_mut()`, here is a second borrow.
}
} else {
// some other logic
break
}
Is there some better way to wrote such implementation?
What's more, is it possible to combine if-let chain with normal conditions? In the same question, I have to wrote the same fragment twice:
if let Some(mut x)=finish.peek_mut(){
if x[0]+price>=0 {
amount-=x[1];
if amount<0 {
x[1]=-amount;
false
} else {
true
}
} else {
append.push([price,amount]);
break
}
} else {
append.push([price,amount]);
break
}
is there some syntax sugar that allow us to wrote things like:
if (let Some(mut x)=finish.peek_mut()) && x[0]+price>=0 {
amount-=x[1];
if amount<0 {
x[1]=-amount;
false
} else {
true
}
} else {
append.push([price,amount]);
break
}
the question is here full code is shown below:
impl Solution {
pub fn get_number_of_backlog_orders(orders: Vec<Vec<i32>>) -> i32 {
let [mut buy,mut sell]=[std::collections::BinaryHeap::<[i32;2]>::new(),std::collections::BinaryHeap::<[i32;2]>::new()];
orders.iter().for_each(|x|{
if let [mut price,mut amount, order_type]=x[0..3]{
let [finish,append]=if order_type==1 {
price=-price;
[&mut buy,&mut sell]
}else{
[&mut sell,&mut buy]
};
while amount>0 {
if if let Some(mut x)=finish.peek_mut(){
if x[0]+price>=0 {
amount-=x[1];
if amount<0 {
x[1]=-amount;
false
} else {
true
}
} else {
append.push([price,amount]);
break
}
} else {
append.push([price,amount]);
break
} {
finish.pop();
}
}
}
});
((buy.into_iter().map(|[a,b]|b as i64).sum::<i64>()+sell.into_iter().map(|[a,b]|b as i64).sum::<i64>()) % 10_0000_0007i64) as i32
}
}