numbers: Basic module structure
This commit is contained in:
parent
5ced705083
commit
55813e4464
1 changed files with 69 additions and 0 deletions
|
@ -2,4 +2,73 @@
|
||||||
|
|
||||||
```idris
|
```idris
|
||||||
module Parser.Numbers
|
module Parser.Numbers
|
||||||
|
|
||||||
|
import public Parser
|
||||||
|
|
||||||
|
import Data.Vect
|
||||||
|
import Control.Eff
|
||||||
|
```
|
||||||
|
|
||||||
|
## Base Abstraction
|
||||||
|
|
||||||
|
```idris
|
||||||
|
public export
|
||||||
|
record Base where
|
||||||
|
constructor MkBase
|
||||||
|
base : Nat
|
||||||
|
digits : Vect base Char
|
||||||
|
%name Base b
|
||||||
|
|
||||||
|
export
|
||||||
|
hasDigit : Base -> Char -> Bool
|
||||||
|
hasDigit (MkBase base digits) c = any (== c) digits
|
||||||
|
|
||||||
|
export
|
||||||
|
digitValue : Base -> Char -> Maybe Nat
|
||||||
|
digitValue (MkBase base digits) c = digitValue' digits 0
|
||||||
|
where
|
||||||
|
digitValue' : Vect n Char -> (idx : Nat) -> Maybe Nat
|
||||||
|
digitValue' [] idx = Nothing
|
||||||
|
digitValue' (x :: xs) idx =
|
||||||
|
if x == c
|
||||||
|
then Just idx
|
||||||
|
else digitValue' xs (S idx)
|
||||||
|
|
||||||
|
public export
|
||||||
|
base10 : Base
|
||||||
|
base10 = MkBase 10
|
||||||
|
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||||
|
|
||||||
|
public export
|
||||||
|
hex : Base
|
||||||
|
hex = MkBase 16
|
||||||
|
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
|
||||||
|
```
|
||||||
|
|
||||||
|
## Parsers
|
||||||
|
|
||||||
|
### Nat
|
||||||
|
|
||||||
|
```idris
|
||||||
|
export
|
||||||
|
nat : Parser Nat
|
||||||
|
```
|
||||||
|
|
||||||
|
## Unit tests
|
||||||
|
|
||||||
|
Test roundtripping a value through the provided parser
|
||||||
|
|
||||||
|
```idris
|
||||||
|
roundtrip : Eq a => Show a => a -> (p : Parser a) -> IO Bool
|
||||||
|
roundtrip x p = do
|
||||||
|
let string = show x
|
||||||
|
putStrLn "Roundtripping \{string}"
|
||||||
|
Just state <- newInternalIO string
|
||||||
|
| _ => do
|
||||||
|
putStrLn "Failed to produce parser for \{string}"
|
||||||
|
pure False
|
||||||
|
Right result <- runEff (rundownFirst p) [handleParserStateIO state] {m = IO}
|
||||||
|
| Left err => ?show_err
|
||||||
|
putStrLn "Input: \{string} Output: \{show result}"
|
||||||
|
pure $ x == result
|
||||||
```
|
```
|
||||||
|
|
Loading…
Add table
Reference in a new issue