Skip to content

Instantly share code, notes, and snippets.

@timmarinin
Last active April 1, 2018 18:44
Show Gist options
  • Save timmarinin/60551c97d0b791a71f4d693b9165dcf1 to your computer and use it in GitHub Desktop.
Save timmarinin/60551c97d0b791a71f4d693b9165dcf1 to your computer and use it in GitHub Desktop.
Guess number / PragProg Elixir 1.6
defmodule Chop do
def guess(n, range) do
mid = middle_of range
IO.puts("Is it #{mid}?")
attempt n, middle_of(range), range
end
def attempt(n, guess, _range) when n == guess do
IO.puts n
end
def attempt(n, guess, range) when n < guess do
IO.puts("No, too high.")
guess(n, lower_half_of range)
end
def attempt(n, guess, range) when n > guess do
IO.puts "No, too low."
guess n, higher_half_of range
end
def middle_of(range) do
a..b = range
a + div b - a, 2
end
def lower_half_of(range) do
a.._b = range
a..middle_of range
end
def higher_half_of(range) do
_a..b = range
middle_of(range)..b
end
end
mt@MacBook-Pro-Timofej:~/Learning/pragelixir% iex
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.6.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> c "chop.exs"
[Chop]
iex(2)> Chop.guess(273, 1..1000)
Is it 500?
No, too high.
Is it 250?
No, too low.
Is it 375?
No, too high.
Is it 312?
No, too high.
Is it 281?
No, too high.
Is it 265?
No, too low.
Is it 273?
273
:ok
iex(3)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment