-
-
Save eduardoejp/8f966ebe09c57b6dfc7fca6d3a43f283 to your computer and use it in GitHub Desktop.
Arithmetic example for Compiler Spotlight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(.require | |
[library | |
[lux (.except) | |
[program (.only program)] | |
["[0]" debug] | |
[abstract | |
[monad (.only do)]] | |
[control | |
["[0]" try] | |
["[0]" io] | |
["p" parser (.use "[1]#[0]" monad)]] | |
[data | |
["[0]" text (.only) | |
["%" \\format] | |
["t" \\parser (.only Parser)]]] | |
[math | |
[number | |
["[0]" nat] | |
["[0]" int]]]]]) | |
(def natural | |
(Parser Nat) | |
(do p.monad | |
[digits (t.many t.decimal)] | |
(p.lifted (at nat.decimal decoded digits)))) | |
(def sign | |
(Parser Int) | |
(all p.either | |
(p.after (t.this "+") (p#in +1)) | |
(p.after (t.this "-") (p#in -1)) | |
(p#in +1))) | |
(def integer | |
(Parser Int) | |
(do p.monad | |
[sign sign | |
natural natural] | |
(in (int.* sign (.int natural))))) | |
(def operation | |
(Parser (-> Int Int Int)) | |
(all p.either | |
(p.after (t.this "+") (p#in int.+)) | |
(p.after (t.this "-") (p#in int.-)) | |
(p.after (t.this "*") (p#in int.*)) | |
(p.after (t.this "/") (p#in int./)) | |
(p.after (t.this "%") (p#in int.%)))) | |
(def white_space | |
(Parser Text) | |
(t.many t.space)) | |
(def calculator | |
(Parser Int) | |
(do p.monad | |
[subject integer] | |
(loop (again [so_far subject]) | |
(p.either (p.after t.end (in so_far)) | |
(do p.monad | |
[_ white_space | |
operation operation | |
_ white_space | |
parameter integer] | |
(again (operation parameter so_far))))))) | |
(def main | |
(program args | |
(io.io (|> (do try.monad | |
[result (t.result calculator (text.interposed " " args))] | |
(in (%.int result))) | |
(try.else "???") | |
debug.log!)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment