File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
chapter24/learning-parsers/src/Text Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ {-# LANGUAGE OverloadedStrings #-}
2
+ module Text.Fractions where
3
+
4
+ import Control.Applicative
5
+ import Data.Ratio ((%) )
6
+ import Text.Trifecta
7
+
8
+ badFraction = " 1/0"
9
+ alsoBad = " 10"
10
+ shouldWork = " 1/2"
11
+ shouldAlsoWork = " 2/1"
12
+
13
+ parseFraction :: Parser Rational
14
+ parseFraction = do
15
+ numerator <- decimal
16
+ char ' /'
17
+ denominator <- decimal
18
+ case denominator of
19
+ 0 -> fail " Cannot divide by zero"
20
+ _ -> return (numerator % denominator)
21
+
22
+ main = do
23
+ print $ parseString parseFraction mempty badFraction
24
+ print $ parseString parseFraction mempty alsoBad
25
+ print $ parseString parseFraction mempty shouldWork
26
+ print $ parseString parseFraction mempty shouldAlsoWork
You can’t perform that action at this time.
0 commit comments