Skip to content

Instantly share code, notes, and snippets.

@xiaohanyu
Last active October 22, 2016 17:05
Show Gist options
  • Save xiaohanyu/e64111caec52709237ee8633b3f54085 to your computer and use it in GitHub Desktop.
Save xiaohanyu/e64111caec52709237ee8633b3f54085 to your computer and use it in GitHub Desktop.
A binary search demo in Elixir(from "Programming Elixir" book, Chapter 6)
defmodule Chop do
def guess(final, range) do
low..high = range
middle = div(low + high, 2)
_guess_helper(final, low, high, middle)
end
defp _guess_helper(final, _low, _high, middle) when final === middle do
middle
end
defp _guess_helper(final, low, _high, middle) when final < middle do
IO.puts "Is it #{middle}"
_guess_helper(final, low, middle, div(low + middle, 2))
end
defp _guess_helper(final, _low, high, middle) when final > middle do
IO.puts "Is it #{middle}"
_guess_helper(final, middle, high, div(middle + high, 2))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment