-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ch24_Fractions.hs
52 lines (42 loc) · 1.33 KB
/
Ch24_Fractions.hs
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Fractions where
import Control.Applicative
import Data.Attoparsec.Text (parseOnly)
import Data.Ratio ((%))
import Data.String (IsString)
import Text.Trifecta
badFraction :: IsString s => s
badFraction = "1/0"
alsoBad :: IsString s => s
alsoBad = "10"
shouldWork :: IsString s => s
shouldWork = "1/2"
shouldAlsoWork :: IsString s => s
shouldAlsoWork = "2/1"
parseFraction :: (Monad m, TokenParsing m) => m Rational
parseFraction = do
numerator <- decimal
char '/'
denominator <- decimal
return (numerator % denominator)
parseFraction' :: (Monad m, TokenParsing m) => m Rational
parseFraction' = do
numerator <- decimal
char '/'
denominator <- decimal
case denominator of
0 -> fail "Denominator can't be zero"
_ -> return (numerator % denominator)
main :: IO ()
main = do
-- parseOnly is Attoparsec
print $ parseOnly parseFraction' badFraction
print $ parseOnly parseFraction' shouldWork
print $ parseOnly parseFraction' shouldAlsoWork
print $ parseOnly parseFraction' alsoBad
-- parseString is Trifecta
print $ parseString parseFraction' mempty badFraction
print $ parseString parseFraction' mempty shouldWork
print $ parseString parseFraction' mempty shouldAlsoWork
print $ parseString parseFraction' mempty alsoBad