Last active
December 18, 2020 22:25
-
-
Save ntreu14/2022f93ce7c5372c8d54b1c24cf52f25 to your computer and use it in GitHub Desktop.
Parser for Advent of Code 2020 Day 18
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System.IO | |
open FParsec | |
// parsers | |
let parseDecimal : Parser<decimal, unit> = puint64 |>> decimal | |
let strWs s = pstring s >>. spaces | |
let parseTerm expression = (parseDecimal .>> spaces) <|> between (strWs "(") (strWs ")") expression | |
let runParser expr str = | |
match run expr str with | |
| Success (result, _, _) -> result | |
| Failure (errorMsg, _, _) -> failwithf "Error from parser: %s" errorMsg | |
let runPart addOperator input = | |
let opp = OperatorPrecedenceParser<decimal, unit, unit>() | |
let expression = opp.ExpressionParser | |
let multOperator = InfixOperator ("*", spaces, 1, Associativity.Left, (*)) | |
opp.TermParser <- parseTerm expression | |
opp.AddOperator(addOperator) | |
opp.AddOperator(multOperator) | |
input | |
|> Array.sumBy (runParser expression) | |
|> printfn "%A" | |
let input = File.ReadAllLines "input.txt" | |
runPart (InfixOperator ("+", spaces, 1, Associativity.Left, (+))) input | |
runPart (InfixOperator ("+", spaces, 2, Associativity.Left, (+))) input |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment