Doubts about matching Range in Elixir pattern matching
my doubt is that the Range matches
in these two functions.
I tested that the following code can be executed (segmented lookup):
defmodule Chop do
def guess(actual, range = low..high) do
guess = div(low+high, 2)
IO.puts "Is it -sharp{guess}?"
_guess(actual, guess, range)
end
defp _guess(actual, actual, _),
do: IO.puts "Yes, it"s -sharp{actual}"
defp _guess(actual, guess, _low..high)
when guess < actual,
do: guess(actual, guess+1..high)
defp _guess(actual, guess, low.._high)
when guess > actual,
do: guess(actual, low..guess-1)
end
Chop.guess(271, 1..1000)
"""
Is it 500?
Is it 250?
Is it 375?
Is it 312?
Is it 281?
Is it 265?
Is it 273?
Is it 269?
Is it 271?
Yes, it"s 271
"""
do not understand how _ low..high and low.._high perform the match, for example, if the incoming interval is 1.. 50, is the matching effect of
not the same? Thank you very much for the answer.
That's easy. Let me flip this song for you:
defmodule Chop do
def guess(actual, range = low..high) do
guess = div(low+high, 2)
IO.puts "Is it -sharp{guess}?"
_guess(actual, guess, range)
end
defp _guess(actual, guess, low..high) do
cond do
guess == actual -> IO.puts "Yes, it's -sharp{actual}"
guess < actual -> guess(actual, guess+1..high)
guess > actual -> guess(actual, low..guess-1)
end
end
end
Chop.guess(271, 1..1000)
this program is equivalent on the computer, but one is conditional clause
, and the other is pattern matching
.
its reality
defp _guess(actual, actual, _),
do: IO.puts "Yes, it's -sharp{actual}"
defp _guess(actual, guess, _low..high)
when guess < actual,
do: guess(actual, guess+1..high)
defp _guess(actual, guess, low.._high)
when guess > actual,
do: guess(actual, low..guess-1)
it is a pattern matching
, but you just need to realize that guess > actual
, guess > actual
, and other arbitrary cases (in this case, only equality) exist as conditions for match.
you can also rewrite another pattern matching
, that is, case guess do
, which is completely equivalent, depending on your own taste. You prefer case
ha when you write standard ml.
maybe you are not familiar with pattern matching
, just write more. One of the essence of elixir is pattern matching
. You can use patter matching
in the future, sometimes it will be less efficient than defining the local quota (typically let in
in sml), but it can be very expensive. Very beautiful . Discover the beauty of elixir. The big door of, functional programming is waiting for you to open
.