henrique-marcomini-m

henrique-marcomini-m

I have the following code:


defp has_char_in_string?(value), do: Regex.match?(~r/[^\d]/, value)

def somefun(arg) do
  
  case has_char_in_string?(arg) do
    true -> foo()
    false -> bar()
  end

end

And I really want to keep this regex within this module and do not externalize this logic. But I also want to use pattern matching or guards instead of a case. Is this even possible? And if it is, how?

Thanks in advance

Showing Posts 1 to 10

NobbZ

NobbZ

No, there is no way to make this regex or even something semantically equivalent into a guardsave predicate.

peerreynders

peerreynders

Probably not what you are looking for:

def somefun(true),
  do: foo()

def somefun(false),
  do: bar()

def somefun(arg) when is_binary(arg),
  do: Regex.match?(~r/[^\d]/, arg)
      |> somefun()

or

defp p_somefun(true),
  do: foo()

defp p_somefun(false),
  do: bar()

def somefun(arg) when is_binary(arg) do
  Regex.match?(~r/[^\d]/, arg)
  |> p_somefun()
end
al2o3cr

al2o3cr

It’s possible, especially if the regular expression is simple - you can translate the regex into its corresponding finite state machine and represent that with pattern matching:

defmodule RegexRecursion do
  def somefun(arg) do
    call_bar(arg)
  end

  defp call_bar("0" <> rest), do: call_bar(rest)
  defp call_bar("1" <> rest), do: call_bar(rest)
  defp call_bar("2" <> rest), do: call_bar(rest)
  defp call_bar("3" <> rest), do: call_bar(rest)
  defp call_bar("4" <> rest), do: call_bar(rest)
  defp call_bar("5" <> rest), do: call_bar(rest)
  defp call_bar("6" <> rest), do: call_bar(rest)
  defp call_bar("7" <> rest), do: call_bar(rest)
  defp call_bar("8" <> rest), do: call_bar(rest)
  defp call_bar("9" <> rest), do: call_bar(rest)

  defp call_bar(""), do: bar()
  defp call_bar(x) when is_binary(x), do: foo()

  defp foo(), do: IO.puts("foo")
  defp bar(), do: IO.puts("bar")
end

Here, the regex [^\d] translates to a state machine that stays in call_bar as long as each character is 0-9, actually calls bar given an empty string, and calls foo otherwise.

If the regex doesn’t involve backreferences or lookaheads (so it’s a theory-of-languages regular expression), it’s always possible to do this.

HOWEVER

The example above is a good example of how this approach obfuscates what should have been code like this:

defmodule RegexRecursionSimple do
  def somefun(arg) when is_binary(arg) do
    if Regex.match?(~r/[^\d]/, arg) do
      foo()
    else
      bar()
    end
  end

  defp foo(), do: IO.puts("foo")
  defp bar(), do: IO.puts("bar")
end

I’m very curious what’s motivating the preference for pattern matching here; it’s not the right tool for the job.

hauleth

hauleth

TBH I would say that Regex is overkill there. And your pattern match can be improved:

def somefun(<<num>> <> rest) when num in ?0..?9, do: call_bar(rest)
def somefun(""), do: bar()
def somefun(bin) when is_binary(bin), do: foo()

The problem with regular expressions the use backtracking engine (and PCRE is such engine) is that it can explode to O(n^2) with some expressions (namely nested wildcard matches). And such cases have been spotted on the wild with pretty simple expressions.

henrique-marcomini-m

henrique-marcomini-m OP

Well I think there is no pretty solution here. Though Hauleth presented something that would work ,I now see that the best way is through a well crafted regex. Thank you all for the answers.

kip

kip

ex_cldr Core Team

I have a package called ex_cldr_unicode that includes guards for

These all operate on the Unicode character classes so it covers what passes for a digit in a more complete sense. It might help or give you some ideas.

Note that it works on code points since there is a limited set of underlying functions that can be used in guards.

There is another bunch of functions that might be helpful, including Cldr.Unicode.alphanumeric?/1 which will return a boolean and also uses the full Unicode definitions (not just Latin1):

iex> Cldr.Unicode.alphanumeric? "1st"
true

iex> Cldr.Unicode.alphanumeric? "KeyserSöze1995"
true

iex> Cldr.Unicode.alphanumeric? "3段"                 
true
mudasobwa

mudasobwa

Creator of Cure

The above might be written as:

defmodule RegexRecursion do
  Enum.each(?0..?9, fn char ->
    defp call_bar(<<unquote(char), rest :: binary>>), do: call_bar(rest)
  end)
end
dkuku

dkuku


is there a way to use guard clauses from erlang ??
I just found this in erlang masterclass course from kent university and I’m trying to solve the problems in elixir - looks similiar as op

peerreynders

peerreynders

https://hexdocs.pm/elixir/guards.html

e.g.

def parse([ch|rest]) when ?a =< ch and ch =< ?z do
  {succeeds, remainder} = get_while(&is_alpha/1, rest)
  {{:var, List.to_atom([ch|succeeds])}, remainder}
end
dkuku

dkuku

thanks @peerreynders - I found a workaround which probably also can be used:
(I’m using double quoted strings for that)

defmodule Guards do
  defguard is_lower(ch) when ch in ~w(q w e r t y u i o p a s d f g h j k l z x c v b n m)
  defguard is_digit(ch) when ch in ~w(1 2 3 4 5 6 7 8 9 0)
end

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
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
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
psy-q
I’m trying to set up Emacs with elixir-ls via lsp-mode and credo via Flycheck. This should mostly be preconfigured as Flycheck picks up c...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews