Convert "case do" to "if"

Hello all!

To make it quick: How can I can convert the following “case” code to something that works with an “if”?

def check_xml_lint() do
  case System.cmd("which", ["xmllint"]) do
    {_, 0} -> true
    _ -> false
  end
end

Following code doesn’t work :confused:

def check_xml_lint() do
  {_, 0} == System.cmd("which", ["xmllint"])
end

Any ideas are appreciated, since I am a perfectionist in programming such things :smile:

Benjamin

1 Like
def check_xml_lint() do
    elem(System.cmd("which", ["xmllint"]), 1) == 0
end

Or maybe…

def check_xml_lint() do
    successful_exit?(System.cmd("which", ["xmllint"]))
end

defp successful_exit?({_, 0}), do: true
defp successful_exit?(_), do: false
1 Like

The question is how often do you find yourself reaching for an if? In Erlang if works like this:

is_greater_than(X, Y) ->
  if
    X>Y ->
      true;
    true -> % works as an 'else' branch
      false
  end

It makes it abundantly clear that in a functional language if simply selects one of two possible expressions/values.

In imperative programming if is typically used to specify separate statement blocks each representing mutually exclusive execution paths which is a bit different - leading sometimes to extreme positions like the Anti-IF campaign.

Functional programming languages are expression based - not statement based.

In OO you replace conditional with polymorphism and in functional programming you sometimes replace a conditional with lambdas.

2 Likes
def check_xml_lint() do
  match?({_, 0}, System.cmd("which", ["xmllint"]))
end
4 Likes

The irony is:

defmacro match?(pattern, expr) do
    quote do
      case unquote(expr) do
        unquote(pattern) ->
          true
        _ ->
          false
      end
    end
  end

And for good measure this is the core of if:

defp build_if(condition, do: do_clause) do
  build_if(condition, do: do_clause, else: nil)
end

defp build_if(condition, do: do_clause, else: else_clause) do
  optimize_boolean(quote do
    case unquote(condition) do
      x when x in [false, nil] -> unquote(else_clause)
      _ -> unquote(do_clause)
    end
  end)
end

So in a way the special form cond/1 is closer to the spirit of a conventional if - but it’s still an expression (and hence the (at least initially) odd looking true -> branch).

4 Likes

Thanks to all of you for your answers!

Coming from an OOP background the following makes perfectly sense:

The replacement of conditionals with lambdas looks even more elegant, than polymorphism does.

2 Likes