use clingo::{
control, Configuration, ConfigurationType, Control, Id, Model, Part, ShowType, SolveMode,
};
use std::env;
fn print_prefix(depth: u8) {
println!();
for _ in 0..depth {
print!(" ");
}
}
fn print_configuration(conf: &Configuration, key: Id, depth: u8) {
let configuration_type = conf.configuration_type(key).unwrap();
if configuration_type.contains(ConfigurationType::VALUE) {
let value = conf
.value_get(key)
.expect("Failed to retrieve statistics value.");
print!("{}", value);
} else if configuration_type.contains(ConfigurationType::ARRAY) {
let size = conf
.array_size(key)
.expect("Failed to retrieve statistics array size.");
for i in 0..size {
let subkey = conf
.array_at(key, i)
.expect("Failed to retrieve statistics array.");
print_prefix(depth);
print!("{}: ", i);
print_configuration(conf, subkey, depth + 1);
}
} else if configuration_type.contains(ConfigurationType::MAP) {
let size = conf.map_size(key).unwrap();
for i in 0..size {
let name = conf.map_subkey_name(key, i).unwrap();
let subkey = conf.map_at(key, name).unwrap();
print_prefix(depth);
print!("{}: ", name);
print_configuration(conf, subkey, depth + 1);
}
} else {
eprintln!("Unknown ConfigurationType");
unreachable!()
}
}
fn print_model(model: &Model) {
let atoms = model
.symbols(ShowType::SHOWN)
.expect("Failed to retrieve symbols in the model.");
print!("Model:");
for symbol in atoms {
print!(" {}", symbol);
}
println!();
}
fn solve(ctl: Control) {
let mut handle = ctl
.solve(SolveMode::YIELD, &[])
.expect("Failed retrieving solve handle.");
loop {
handle.resume().expect("Failed resume on solve handle.");
match handle.model() {
Ok(Some(model)) => print_model(model),
Ok(None) => break,
Err(e) => panic!("Error: {}", e),
}
}
handle
.get()
.expect("Failed to get result from solve handle.");
handle.close().expect("Failed to close solve handle.");
}
fn main() {
let options = env::args().skip(1).collect();
let mut ctl = control(options).expect("Failed creating Control.");
{
let conf = ctl.configuration_mut().unwrap();
let root_key = conf.root().unwrap();
print_configuration(conf, root_key, 0);
println!("\n");
let mut sub_key;
sub_key = conf.map_at(root_key, "solve.models").unwrap();
conf.value_set(sub_key, "0")
.expect("Failed to set solve.models to 0.");
sub_key = conf.map_at(root_key, "solver").unwrap();
sub_key = conf.array_at(sub_key, 0).unwrap();
sub_key = conf.map_at(sub_key, "heuristic").unwrap();
conf.value_set(sub_key, "berkmin")
.expect("Failed to set heuristic to berkmin.");
}
ctl.add("base", &[], "a :- not b. b :- not a.")
.expect("Failed to add a logic program.");
let part = Part::new("base", vec![]).unwrap();
let parts = vec![part];
ctl.ground(&parts)
.expect("Failed to ground a logic program.");
solve(ctl);
}