dikaiosune's answer explains the problem: the resulting type of your if is (), which is being returned instead of a bool.
Here's a few ways of writing the code a bit more idiomatically:
I'd start by writing it with implicit returns:
fn recursive_binary_search<T: Ord + Eq>(list: &[T], target: T) -> bool {
if list.len() < 1 {
return false;
}
let guess = list.len() / 2;
if target == list[guess] {
true
} else if list[guess] > target {
recursive_binary_search(&list[0..guess], target)
} else {
recursive_binary_search(&list[guess..list.len()], target)
}
}
Then I'd perform the compare just once, instead of potentially twice. Could save a bit of time if comparisons are expensive, but it also looks nice with the match:
use std::cmp::Ordering;
fn recursive_binary_search<T: Ord + Eq>(list: &[T], target: T) -> bool {
if list.is_empty() {
return false;
}
let guess = list.len() / 2;
match target.cmp(&list[guess]) {
Ordering::Less => recursive_binary_search(&list[..guess], target),
Ordering::Greater => recursive_binary_search(&list[guess..], target),
Ordering::Equal => true,
}
}
You can also drop the beginning and end parts of the ranges, and use is_empty for the guard clause.
Then there's the problem of the stack overflow if you search for a value larger than the biggest value... you need to ignore the pivot when recurring:
use std::cmp::Ordering;
fn recursive_binary_search<T: Ord>(list: &[T], target: T) -> bool {
if list.is_empty() {
return false;
}
let guess = list.len() / 2;
match target.cmp(&list[guess]) {
Ordering::Less => recursive_binary_search(&list[..guess], target),
Ordering::Greater => recursive_binary_search(&list[guess+1..], target),
Ordering::Equal => true,
}
}
fn main() {
assert!(!recursive_binary_search(&[1,2,3,4,5], 0));
assert!(recursive_binary_search(&[1,2,3,4,5], 1));
assert!(recursive_binary_search(&[1,2,3,4,5], 2));
assert!(recursive_binary_search(&[1,2,3,4,5], 3));
assert!(recursive_binary_search(&[1,2,3,4,5], 4));
assert!(recursive_binary_search(&[1,2,3,4,5], 5));
assert!(!recursive_binary_search(&[1,2,3,4,5], 6));
}
If you aren't implementing this for learning purposes, use the built-in binary_search.