How to call "case/cond" over String.starts_with?(a) ?

I want to call a normal function and do a pattern matching over it, such as:

res = String.starts_with?(a)
case res do
  "a" -> # ....
  "b" -> # ....
  "c" -> # ....
  "d" -> # ....
  _ ->  # .......
end

But this thing isn’t supported in Ellixir, is it? What’be be an alternative then?

For this particular use case you can use regular pattern matching:

case a do
  "a" <> _ -> # ...
end
4 Likes

It is possible, just you use that function wrongly:

res = String.starts_with?(str, prefix)

case res do
  true -> # …
  false -> # …
end
4 Likes

It looks like you want String.first/1:

case String.first(input) do
  "a" -> # ....
  "b" -> # ....
  "c" -> # ....
  "d" -> # ....
  nil ->  # input was an empty string
end

This type of case matching is totally acceptable (but hopefully you won’t make 27 different clauses for it!)

3 Likes