madlisp/mad/calc.mad

57 lines
1.8 KiB
Plaintext
Raw Normal View History

2020-10-18 04:15:51 +00:00
;;
;; Simple command line calculator which demonstrates the following concepts:
;; - command parser with arguments
;; - readline support with history
;; - main loop
;;
;; This is a barebones example for creating interactive command line scripts.
;; This script should be executed directly, not inside the repl.
;;
;; Define commands
2020-12-06 04:04:04 +00:00
(defn cmdAdd (args) (apply + args))
(defn cmdDiv (args) (apply / args))
(defn cmdMod (args) (apply % args))
(defn cmdMul (args) (apply * args))
(defn cmdSub (args) (apply - args))
(defn cmdHelp () (str "Available commands: " (apply join ", " (keys cmdMap))))
(defn cmdQuit () (exit))
2020-10-18 04:15:51 +00:00
;; And we define a hash-map for command lookups with minimum number of arguments
(def cmdMap {
"add": [cmdAdd 2]
"div": [cmdDiv 2]
2020-12-06 04:04:04 +00:00
"mod": [cmdMod 2]
2020-10-18 04:15:51 +00:00
"mul": [cmdMul 2]
"sub": [cmdSub 2]
"help": [cmdHelp 0]
"quit": [cmdQuit 0]
2020-10-18 04:15:51 +00:00
})
;; Find the first command which starts with the given name, or null
2020-12-06 04:04:04 +00:00
(defn findCmd (name)
2020-10-18 04:15:51 +00:00
(if (empty? name) null
(let (matches (filterh (fn (v k) (prefix? k name)) cmdMap))
(if (empty? matches) null
2020-12-06 04:04:04 +00:00
(get matches (first (keys matches)))))))
2020-10-18 04:15:51 +00:00
;; Split input by spaces, find command that matches the first word
;; and call it, giving the rest of the words as arguments.
2020-12-06 04:04:04 +00:00
(defn parseInput (inp)
2020-10-18 04:15:51 +00:00
(let (words (split " " inp) cname (first words) args (tail words) cmd (findCmd cname))
(if (null? cmd) "Unknown command, try 'help'."
(if (< (len args) (second cmd)) (str "Give at least 2 arguments to " cname ".")
2020-12-06 04:04:04 +00:00
((first cmd) args)))))
2020-10-18 04:15:51 +00:00
;; Define a file for readline and load it
2020-10-18 06:32:20 +00:00
(def readlineFile (str HOME "calc_history"))
2020-10-18 07:45:49 +00:00
(readline-load readlineFile)
2020-10-18 04:15:51 +00:00
;; Main loop: Read input from user, add it to readline, and parse it
2020-12-12 07:53:48 +00:00
(while true
2020-12-06 04:04:04 +00:00
(let (inp (readline "[calc] "))
2020-12-12 07:53:48 +00:00
(readline-add inp)
(readline-save readlineFile)
(print "⇒ " (parseInput inp) EOL)))