Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pattern match for "any string"?

Tags:

elixir

In Elixir, I'd like to pattern match for the presence of a field in a struct - either where the field is not nil, or even better, where it is a string.

I know how pattern match a struct where the field is nil. For example:

def run(%Query{expression: nil})

How can I match structs where the given field is any string?

like image 451
Nathan Long Avatar asked Oct 26 '25 12:10

Nathan Long


1 Answers

You can match with:

Kernel.match?("" <> rest , "")
#true

def run(%Query{expression: "" <> expression})

Or you can use a guard for this:

Kernel.match?(foo when is_binary(foo), nil)
#false

def run(%Query{expression: expression}) when is_binary(expression)

A list of valid guard clauses is available at http://elixir-lang.org/getting-started/case-cond-and-if.html#expressions-in-guard-clauses

like image 91
Gazler Avatar answered Oct 28 '25 02:10

Gazler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!