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
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.
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