Elixir 練習問題 ModulesAndFunctions-6

今度のは一種の数あて問題だ。

defmodule Chop do

  def guess(actual, a..b) do
    g = div(a + b, 2)
    _guess(actual, a..b, g)
  end

  def _guess(actual, _, g) when actual == g do
    IO.puts("It is " <> to_string(g))
    IO.puts(g)
  end
  def _guess(actual, a.._, g) when actual < g do
    IO.puts("It is " <> to_string(g))
    guess(actual, a..(g - 1))
  end
  def _guess(actual, _..b, g) do
    IO.puts("It is " <> to_string(g))
    guess(actual, (g + 1)..b)
  end

end
^o^ > iex practice_6_6.exs
Eshell V8.0  (abort with ^G)
Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Chop.guess(273, 1..1000)
It is 500
It is 250
It is 375
It is 312
It is 281
It is 265
It is 273
273
:ok

あれ、関数の戻り値が表示されちゃうな。まあ、いいか。