rkr

rkr

Pattern-matching char-lists

Hi,

whats the correct way to match a char-list against another charlist, but as a variable? Like so:

input = 'Hello World! {{ }} {% %}'
pattern = '{{'
...
case input do
    ^pattern ++ remaining ->
        ...
end

but this isn’t working.

Context:
I currently try to build a parser for twig-like templates to reuse code I already have, but mostly for learning purposes as I’ve never came in touch with elixir or erlang before. Erlang already comes with leex and yecc, but they (or I) struggle with context-switching (programs embedded in text-content). So I try to build a very light-weight parser to tell the content-context and program-context apart and then use leex/yecc to parse the program-islands.
Twig-templates might look like this:
Hi, my name is {{ person.name }} and I am {{ person.years }} year{% person.years != 1 ? ‘s’ : ‘’ %} old.
{% include ‘@common/details.twig’ with person %}

Since the opening-tags are configurable, I have a special case, where I’m stuck at and I dont manage to find help online.

At the most fundamental level, I have a function that should tell me, whats the first occurence of a list of char-sequences (char-list).

Like template |> MyScanner.get_next_position_of({'{{', '{%', '{#'}) to find the nearst opening-tag in my template to toggle the twig-context.

Now inside the get_next_position_of-function, I thought I could simply use recursion to step through all chars in the template and use pattern-matching to check, if the upcoming sequence of characters matches one of the patterns, I gave as the argument.

Marked As Solved

michalmuskala

michalmuskala

I think the only way to do this with charlists is to go element-by-element in a loop. Something like:

input = 'Hello World! {{ }} {% %}'
pattern = '{{'
consume_pattern(input, pattern)

defp consume_pattern([c | input], [c | pattern]), do: consume_pattern(input, pattern)
defp consume_pattern(input, []), do: {:ok, input}
defp consume_pattern(_input, pattern), do: {:unmatched, pattern}

Also Liked

jordiee

jordiee

https://elixir-lang.org/getting-started/pattern-matching.html

Under the The pin operator section it talks about a variable being used more then once in a pattern match.

rkr

rkr

Thank you!

Would have been great if I could express it the way I wanted to, but this also works and I found a working solution.
Now even templates like Twig.PreParser.parse('<html>{{ fn({test: {}}) }}</html>', my_tags) could be parsed correctly. I have no idea how inefficient my solution is, but I will eventually find out soon :slight_smile:

[
  {:content, 0, '<html>'},
  {:expr, 8, ' fn({test: {}}) '},
  {:content, 24, '</html>'}
]

Now I finally have to find a solution for strings like "Hello \"World\"!", but I think I already now what to do.

dimitarvp

dimitarvp

Didn’t know about that particular way of duplicating parameters in a function head. Could you please explain this particular line of code or point me to the proper docs?

dimitarvp

dimitarvp

Indeed. I had no idea you can use the same variable in more than one pattern matching clause though. :open_mouth: In this case you basically force string sub-matching by using this mechanism. Damn, I feel like I missed something extremely basic when learning Elixir!

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement