Case with greater than

Hi,

Simple thing but I cannot seem to find it anywhere. How do I do a case with greater than?

As in:

case Kernel.length my_list do
0 ->
{ :ok, :no_data }
> 0 ->
{ :ok, my_list }
_ ->
{ :error, :some_general_error }

Or should I structure my code some other way?

You’d want to use a guard in this case. Which would look like this

case Kernel.length(my_list) do
  0 ->
    { :ok, :no_data }
  n when n > 0 ->
    { :ok, my_list }
  _ ->
    { :error, :some_general_error }

Although Kernel.length/1 would never return a negative value so you’d probably be better off with Enum.empty?/1 for the code you’ve listed.

3 Likes

You can use guards:

case length(my_list) do
  len when len == 0 ->
    { :ok, :no_data }
  len when len > 0 ->
    { :ok, my_list }
  _ ->
    { :error, :some_general_error }
end

Or, you can use multiple function definitions:

defmodule My do

  def proceed([]), do: {:ok, :no_data}
  def proceed(x) when is_list(x), do: {:ok, x}
  def proceed(_), do: { :error, :not_a_list }

end

~/elixir_programs$ iex my.exs
    Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
    Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> My.proceed [1,2,3]
{:ok, [1, 2, 3]}

iex(2)> My.proceed({1, 2})
{:error, :not_a_list}

iex(3)> My.proceed []
{:ok, :no_data}

Or should I structure my code some other way?

defmodule Demo do

  def check_list(list) do
    case list do
      [] ->
        {:ok, :no_data}
      [_|_] ->
        {:ok, list}
      _ ->
        {:error, :some_general_error}
    end
  end

end

IO.inspect(Demo.check_list(1))
IO.inspect(Demo.check_list([]))
IO.inspect(Demo.check_list([1]))
IO.inspect(Demo.check_list([1,2]))
$ elixir demo.exs
{:error, :some_general_error}
{:ok, :no_data}
{:ok, [1]}
{:ok, [1, 2]}
$

I decided to go for the empty? way. Thanks.

2 Likes