Created
April 30, 2016 20:57
-
-
Save rsgrafx/95465ac145db7f6908e5d0a46d11e83a to your computer and use it in GitHub Desktop.
Best use cases for 'with' in elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Bicycle do | |
defstruct [wheels: 2, pedals: nil, seat: nil, pass: nil] | |
end | |
defmodule BikeTypeCheck do | |
def check(%Bicycle{wheels: count, pedals: val}=bike) do | |
return = with {:ok, 2} <- count_wheels(count), | |
{:ok, true} <- has_pedals(val), | |
do: pedal_away(bike) | |
keep_passing_msg = fn | |
{:error, :motorbike} -> handle_motor_bike(bike) | |
{:error, :tricycle} -> handle_tricycle(bike) | |
answer -> IO.inspect(answer) | |
end | |
return |> keep_passing_msg.() | |
end | |
defp count_wheels(2), do: {:ok, 2} | |
defp count_wheels(3), do: {:error, :tricycle} | |
defp count_wheels(_), do: {:error, :not_bike} | |
defp has_pedals(true), do: {:ok, true} | |
defp has_pedals(_), do: {:error, :motorbike} | |
defp pedal_away(bike) do | |
IO.puts "\nONLY TRUE BIKE." | |
%{bike | pass: true} | |
end | |
defp handle_motor_bike(bike) do | |
IO.puts "\nSend Motorbike somewhere." | |
<>"\nscope captured maintained within function its defined?" | |
IO.inspect(bike) | |
end | |
defp handle_tricycle(bike) do | |
IO.puts "\nSend Tricycle somewhere.\n" | |
<>"scope captured maintained within function its defined?" | |
IO.inspect(bike) | |
end | |
end | |
bike = struct(Bicycle, pedals: true, wheels: 2) | |
bike2 = struct(Bicycle, pedals: false, wheels: 2) | |
bike3 = struct(Bicycle, pedals: false, wheels: 3) | |
# Keep passing allong the message | |
# keep_passing_msg = fn | |
# {:error, :motorbike} -> IO.inspect(error) | |
# answer -> IO.inspect(answer) | |
# end | |
BikeTypeCheck.check(bike) #|> keep_passing_msg.() | |
BikeTypeCheck.check(bike2) #|> keep_passing_msg.() | |
BikeTypeCheck.check(bike3) #|> keep_passing_msg.() | |
val = %{height: 10, width: 100, length: 5} | |
work = fn(opts) -> | |
result = | |
with {:ok, w} <- Map.fetch(opts, :width), | |
{:ok, h} <- Map.fetch(opts, :height), | |
{:ok, l} <- Map.fetch(opts, :length), | |
do: h * w * l | |
result | |
|> case do | |
:error -> "Not full match" | |
val -> val | |
end | |
end | |
IO.puts work.(val) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment