-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.rs
32 lines (28 loc) · 869 Bytes
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#![feature(custom_inner_attributes)]#![rustfmt::skip]
use nom::{character::is_digit, *};
pub fn main() {
println!(
"{}",
include_bytes!("../input.txt")
.split(|&b| b == b'\n')
.map(|e| expr(e).unwrap().1)
.sum::<usize>()
);
}
named!(digit<usize>, map!(take_while_m_n!(1, 1, is_digit), |d| (d[0] - b'0') as usize));
named!(unit<usize>, alt!(delimited!(tag!("("), expr, tag!(")")) | digit));
named!(
expr<usize>,
do_parse!(
first: unit
>> sum: fold_many1!(
complete!(pair!(delimited!(tag!(" "), one_of!("+*"), tag!(" ")), unit)),
first,
|acc, (op, num)| match op {
'+' => acc + num,
'*' => acc * num,
_ => unreachable!(),
})
>> (sum)
)
);