Skip to content

Instantly share code, notes, and snippets.

@jcamenisch
Last active January 7, 2016 02:01
Show Gist options
  • Save jcamenisch/6dd7dbe5154dbb879ec9 to your computer and use it in GitHub Desktop.
Save jcamenisch/6dd7dbe5154dbb879ec9 to your computer and use it in GitHub Desktop.
defmodule Chop do
def guess(actual, low..high) do
next_guess = fn
(n) when n == actual -> actual
(n) when n > actual -> guess(actual, low..n)
(n) when n < actual -> guess(actual, n..high)
end
n = div(low + high, 2)
IO.puts "Is it #{n}?"
next_guess.(n)
end
end
@jcamenisch
Copy link
Author

This next_guess function looks an awful lot like a case statement. If we had been introduced to those yet, I think I would write it as such, and move the block to the end of the function.

Or one could simply invoke the function inline in truly anonymous fashion:

defmodule Chop do
  def guess(actual, low..high) do
    half = div(low + high, 2)
    IO.puts "Is it #{half}?"

    (fn
      (n) when n == actual -> actual
      (n) when n  > actual -> guess(actual, low..n)
      (n) when n  < actual -> guess(actual, n..high)
    end).(half)
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment