Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SelectionSearch may fail when asking for nth number outside index range. #30

Closed
ioreskovic opened this issue Jun 27, 2017 · 2 comments
Closed

Comments

@ioreskovic
Copy link
Contributor

ioreskovic commented Jun 27, 2017

Consider following example:
Asking for selectionSearch(List(5, 8, 4, 7, 3, 0, 1, 9, 6, 2), 10) should yield None, since there is no 10th element in 0-indexed list with 10 elements.

However, this call will return Some(9), which is a symptom of the bug in here:

def search(t: (List[A], A, List[A]), m: Int): Option[A] = t match {
    case (Nil, p, Nil) => Some(p)
    case (l, p, g) => select(l, p, g, l.length, m)
}

If you consider the call on singleton list with m outside range it will look like this:
search((Nil, 9, Nil), 1)

Which will return Some(9), even though m is outside the range.

The fix is to use the first pattern with guard if m == 0 and have the one without it that returns None:

def search(t: (List[A], A, List[A]), m: Int): Option[A] = t match {
    case (Nil, p, Nil) if m == 0 => Some(p)
    case (Nil, p, Nil) => None
    case (l, p, g) => select(l, p, g, l.length, m)
}
@vkostyukov
Copy link
Owner

Thanks @ioreskovic! Want to submit a PR with a fix?

@ioreskovic
Copy link
Contributor Author

Sure thing, I'll do it tomorrow 😃

ioreskovic added a commit to ioreskovic/scalacaster that referenced this issue Jun 29, 2017
vkostyukov pushed a commit that referenced this issue Dec 26, 2017
* Bugfix for selecting k-th element outside List bounds

* Indentation alignment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants