elbasti

elbasti

Complicated binary pattern matching in function heads

I’m trying to implement some functionality by pattern matching purely as a learning exercise to familiarize myself with bitstrings/charslists/binaries.

Imagine I want to write a function parse_symbol that takes the symbol for a security and parses it into it’s constituent parts.

A security symbol is a string that looks like this:
"NU 05/19/2023 4.50 P", or "AAPL 03/31/2023 145.00 C"

Each of those symbols is made up of {stock ticker} {expiration date} {strike price} {option type}

So AAPL 03/31/2023 145.00 C is an “apple call option, with a $145 strike price, and an expiration date of 03/31/2023”.

The stock ticker part is of variable length: it could be one character (F is the symbol for the Ford Motor Company) or multiple. The “Option type” could be "C" for a call option or "P" for a put.

It’s relatively simple to write a regex that parses out the components of the symbol. Is it possible to parse them out in a function head by pattern matching?

So something like:

def parse_symbol(<<ticker," ", month,"/",day,"/",year," ",strike," ",type>>) do
    %{ticker: ticker, strike: strike, type: type}
end

Warning: I know that the above code is probably broken/gobledeegook in all sorts of ways, I’m just trying to grok how binaries work :slight_smile:

Marked As Solved

hst337

hst337

It is not possible to write a single pattern to parse this string. However, it is possible to write a pattern for dates matching:

[ticker, date, price, option] = String.split(input, " ")
<<month :: binary-size(2), "/", day :: binary-size(2), "/", year :: binary-size(4)>> = date
price = String.to_float(price) # Or decimal parse
[year, month, day] = Enum.map([year, month, day], &String.to_integer/1)

Also Liked

hst337

hst337

Yes, it is variable length. Binary pattern matching was designed to help in the development of fixed-offset binary protocols.

bottlenecked

bottlenecked

You could if you wanted to… but you’d have to know min and max number of characters for the ticker length.

Example

# ticker of length = 2
<<ticker::binary-size(2)," ",rest::binary>> = "NU 05/19/2023 4.50 P"

#ticker of length = 4
<<ticker::binary-size(4)," ",rest::binary>> = "AAPL 03/31/2023 145.00 C"

So basically you’d have to create as many function heads for parse_symbol/1 as there are variations in the length of the ticker (assuming everything else is of constant length). But this assumption probably doesn’t hold true for the price (again, assuming you’re looking to extract it using pattern matching) - so you’d need to combine with some other approach if you need to read all values out of the security symbol

ntodd

ntodd

I know you are doing this as an exercise, but to me this sounds like a good fit for a parser combinator. Look into how NimbleParsec handles it. You can view the compiled binary pattern matching clauses with debug: true. That might help you with your task.

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
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
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement