File tree 1 file changed +46
-9
lines changed
1 file changed +46
-9
lines changed Original file line number Diff line number Diff line change @@ -553,17 +553,54 @@ t53 = parse expr' "1 + 1 * 3" -- [(Add (Int 1) (Mult (Int 1) (Int 3)),"")]
553
553
554
554
t54 = parse expr' " 1 * 2 + 3" -- [(Add (Mult (Int 1) (Int 2)) (Int 3),"")]
555
555
556
- -- to do
556
+ -- Exercise 6
557
+
558
+ expr'' :: Parser Int
559
+ expr'' = do
560
+ t <- term''
561
+ do
562
+ symbol " +"
563
+ e <- expr''
564
+ return (t + e)
565
+ <|> do
566
+ symbol " -"
567
+ e <- expr''
568
+ return (t - e)
569
+ <|> return t
570
+
571
+ term'' :: Parser Int
572
+ term'' = do
573
+ f <- factor''
574
+ do
575
+ symbol " *"
576
+ t <- term''
577
+ return (f * t)
578
+ <|> do
579
+ symbol " /"
580
+ t <- term''
581
+ return (f `div` t)
582
+ <|> return f
583
+
584
+ factor'' :: Parser Int
585
+ factor'' =
586
+ do
587
+ symbol " ("
588
+ e <- expr''
589
+ symbol " )"
590
+ return e
591
+ <|> integer
592
+
593
+ t61 = parse expr'' " 4 - 2" -- [(2,"")]
594
+
595
+ t62 = parse expr'' " -12" -- [(-12,"")]
596
+
597
+ t63 = parse expr'' " 4 + (-2)" -- [(2,"")]
598
+
599
+ t64 = parse expr'' " 6 / 2" -- [(3,"")]
557
600
558
- -- 6. Extend the parser expr :: Parser Int to support subtraction and division,
559
- -- and to use integer values rather than natural numbers, based upon the fol-
560
- -- lowing revisions to the grammar:
561
- -- expr::“ term p + expr | - expr | q
562
- -- term::“ factor p * term | / term | q
563
- -- factor::“ ( expr ) | int
564
- -- int::“
565
- -- ¨ ¨ ¨ | -1 | 0 | 1 | ¨ ¨ ¨
601
+ t65 = parse expr'' " 5 - (2 / 2)" -- [(4,"")]
566
602
603
+ -- to do
567
604
-- 7. Further extend the grammar and parser for arithmetic expressions to support
568
605
-- exponentiation ^, which is assumed to associate to the right and have higher
569
606
-- priority than multiplication and division, but lower priority than parentheses
You can’t perform that action at this time.
0 commit comments