mercurio

mercurio

I have this function for parsing a string into a tuple. "-<number>" should return {:lat, -<number>}, "+<number>" should return {:lat, <number>}, and "<number>" should return {:gridNum, }`, plus some other simpler matches:

defp parseIndex(s) do
      cond do
        String.match?(s, ~r/^-\d+$/) ->
          [_, n] = Regex.run(~r/^-(\d+)$/, s)
          {:lat, -1 * String.to_integer(n)}
        String.match?(s, ~r/^\+\d+$/) ->
          [_, n] = Regex.run(~r/^\+(\d+)$/, s)
          {:lat, String.to_integer(n)}
        s == "--" ->
          {:latFrame, -1}
        s == "++" ->
          {:latFrame, 1}
        s == "-*" ->
          {:latEnd, -1}
        s == "+*" ->
          {:latEnd, 1}
        match?({_n, ""}, Integer.parse(s)) ->
          {:gridNum, String.to_integer(s)}
        true ->
          {:gridText, s}
      end
    end

This works, but is there a better way to do this without running the regex twice, once to match a pattern like -<number> and then again to extract the numerical portion? Same for the second-to-last clause, which ends up parsing the integer twice.

Thanks!

Phil

Showing Posts 1 to 9

kip

kip

ex_cldr Core Team

Noting that:

  • Regex.run/2 returns nil if there is no match and that
  • nil is falsy for the purposes of boolean evaluation and
  • you can bind a variable in a match

For an optimisation I would likely put the explicit equality checks first since a cond proceeds in lexical order. Also I think you can collapse the :lat parsing into a single clause. And one last one, you can match and bind on the integer parsing too (the second last clause):

defp parseIndex(s) do
  cond do
    s == "--" ->
      {:latFrame, -1}
    s == "++" ->
      {:latFrame, 1}
    s == "-*" ->
      {:latEnd, -1}
    s == "+*" ->
      {:latEnd, 1}
    (match = Regex.run(~r/^([+-]\d+)$/, s)) -> 
      [_, n] = match
      {:lat, String.to_integer(n)}
    match?({n, ""}, Integer.parse(s)) ->
      {:gridNum, n}
    true ->
      {:gridText, s}
  end
end
mercurio

mercurio OP

Thanks! I’d tried

[_, n] = Regex.run(~r/^-(\d+)$/, s) ->
  {:lat, -1 * String.to_integer(n)}

But when the Regex fails [_, n] doesn’t match, causing an error. Your use of the match variable solves that beautifully.

However, the second-to-last clause doesn’t work, because variables within the match?/2 call aren’t available outside. I guess I could use Regex to detect a string of only digits and then use String.to_integer/1, that’s probably slightly faster than parsing the string to an integer twice.

And thanks, also, for pointing out the simple optimization of moving the static clauses to the top.

Phil

code-shoily

code-shoily

This is how I’d do it:

  def parseIndex("--"), do: {:latFrame, -1}
  def parseIndex("++"), do: {:latFrame, -1}
  def parseIndex("-*"), do: {:latEnd, 1}
  def parseIndex(s) do
    case Regex.run(~r/^([+-])?(\d+)$/, s) do
      [_, "", n] -> {:gridNum, String.to_integer(n)}
      [_, "-", n] -> {:lat, -1 * String.to_integer(n)}
      [_, _, n] -> {:lat, String.to_integer(n)}
      nil -> {:gridText, s}
    end
  end

By adding groups to the sign part and the remaining number and inspecting the captured sign (or absence of it), we can remove the need to a check to Integer.parse.

[Update: I had missed the -1 multiplier]

edisonywh

edisonywh

What about doing binary matching directly?

defmodule Hello do
  def run(string) do
    do_run(string)
  end
  
  defp do_run("--"), do: {:latFrame, -1}
  defp do_run("++"), do: {:latFrame, 1}
  defp do_run("-*"), do: {:latEnd, -1}
  defp do_run("+*"), do: {:latEnd, 1}

  defp do_run(<<"+", number::binary>>), do: {:lon, to_integer(number)}
  defp do_run(<<"-", number::binary>>), do: {:lat, -to_integer(number)}
  defp do_run(<<"+", number::binary>>), do: {:lon, to_integer(number)}
  defp do_run(number), do: {:gridNum, to_integer(number)}
  
  defp to_integer(string), do: String.to_integer(string)
end
code-shoily

code-shoily

Lol, I was just thinking about that! I love a set of declarative one-liners where you can scan from top to bottom and pin point the right clause when you see it.

code-shoily

code-shoily

This would raise an error in case of a string though, never matching a {:gridText, text} result.

mercurio

mercurio OP

I like how this avoids the Regex (not that I have anything against Regexes) but <<"+", number::binary>> doesn’t constrain number to be a sequence of digits. It would try to parse something like "+q", which should result in {:gridText, "+q"}.

mercurio

mercurio OP

I like the solution with multiple functions, with a single Regex in the last one after handling all the simple cases. This is the best solution so far, thanks!

hauleth

hauleth

Here you have it with error handling

defmodule Hello do
  def run(string) do
    {:ok, do_run(string)}
  catch
    :throw, error -> {:error, error}
  end
  
  defp do_run("--"), do: {:latFrame, -1}
  defp do_run("++"), do: {:latFrame, 1}
  defp do_run("-*"), do: {:latEnd, -1}
  defp do_run("+*"), do: {:latEnd, 1}

  defp do_run(<<"+", number::binary>>), do: {:lon, to_integer(number)}
  defp do_run(<<"-", number::binary>>), do: {:lat, -to_integer(number)}
  defp do_run(<<"+", number::binary>>), do: {:lon, to_integer(number)}
  defp do_run(number), do: {:gridNum, to_integer(number)}
  
  defp to_integer(string) do
    case Integer.parse(string) do
      {num, ""} -> num
      _ -> throw({:not_number, string})
    end
  end
end
— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
mnkhod
So i have been using ash framework for a while and i love it. However currently the issue im having with ash framework is the error handl...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews