find_rank_with_minimum_cost_imp goalvalue agg_cost rank_parent parent_reverse_state ref_t direction = do t <- val ref_t [size_left, size_right] <- size_children ref_t aux t size_left size_right where aux Leaf _ _ = error "we should have found the goal value already" aux t size_left size_right | min_cost_in_this_tree == goalvalue = return . return $ current_rank | otherwise = do min_cost_l <- compute_min_cost $ l t min_cost_r <- compute_min_cost $ r t case compareMaybe min_cost_l min_cost_r of EQ -> error "rank not found" LT -> find_rank (l t) LeftChild GT -> find_rank (r t) RightChild where min_cost_in_this_tree = icost t + agg_cost agg_cost' = agg_cost + icost t x_reversed = parent_reverse_state ⊕ (reversed (item t)) current_rank = compute_rank rank_parent direction x_reversed parent_reverse_state size_left_node size_right_node find_rank = find_rank_with_minimum_cost_imp goalvalue agg_cost' current_rank x_reversed