Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns rpncore
- (:require [clojure.string :as string]))
- ;make digit sets for number detection
- (def digits (set "0123456789."))
- ;make sure they are a number
- (defn isnumber [N]
- (if (= (count N) 0)
- true
- (let [f (first N)]
- (if (digits f)
- (isnumber (rest N))
- false))))
- ;error class
- (defn error [st]
- (js/alert st)
- (throw (Exception. st)))
- (defn join
- ([List] (join List ""))
- ([List st]
- ))
- (defn caller [nm f n stack]
- (if (>= (count stack) n)
- (if (>= n 0)
- (cons (apply f (take n stack)) (nthnext stack n))
- (f nm stack))
- (error (str nm " takes " n " arguments"))))
- ;---FUNCTIONS-----
- ;add
- (defn add [a b]
- (+ b a))
- (defn sub [a b]
- (- b a))
- (defn mul [a b]
- (* b a))
- (defn div [a b]
- (/ b a))
- (defn sqrt [a]
- (.sqrt js/Math a))
- (defn pow [a b]
- (.pow js/Math b a))
- (defn sin [a]
- (.sin js/Math a))
- (defn cos [a]
- (.cos js/Math a))
- (defn tan [a]
- (.tan js/Math a))
- (defn log [a]
- (.log js/Math a))
- (defn logbase [a b]
- (/ (log b) (log a)))
- (defn iffun [a b c]
- (if (= c 0)
- a
- b))
- (defn gt [a b]
- (if (> b a)
- 1
- 0))
- (defn gte [a b]
- (if (>= b a)
- 1
- 0))
- (defn lt [a b]
- (if (< b a)
- 1
- 0))
- (defn lte [a b]
- (if (<= b a)
- 1
- 0))
- (defn eq [a b]
- (if (= b a)
- 1
- 0))
- (defn dup [nm stack]
- (if (>= (count stack) 1)
- (cons (first stack) stack)
- (error (str nm " requires 1 argument"))))
- (defn pi []
- Math/PI)
- (defn ex []
- Math/E)
- ;Assign the functions to their characters
- (def funcs {"+" [ add 2]
- "add" [ add 2]
- "-" [ sub 2]
- "sub" [ sub 2]
- "*" [ mul 2]
- "mul" [ mul 2]
- "div" [ div 2]
- "/" [ div 2]
- "sqrt" [ sqrt 1]
- "exp" [ pow 2]
- "pow" [ pow 2]
- "ln" [ log 1]
- "sin" [ sin 1]
- "cos" [ cos 1]
- "tan" [ tan 1]
- "pi" [ pi 0]
- "e" [ ex 0]
- "dup" [ dup -1]
- "$" [ dup -1]
- "log" [ logbase 2]
- "if" [ iffun 3]
- "<" [ lt 2]
- "<=" [ lte 2]
- ">" [ gt 2]
- ">=" [ gte 2]
- "=" [ eq 2]
- })
- ;Stacktraverser
- (defn crawler [List stack]
- (if (= (count List) 0)
- stack
- (let [op (first List)]C
- (if (isnumber op)
- (crawler (rest List) (cons (js/parseFloat op) stack))
- (if (contains? funcs op)
- (crawler (rest List) (caller op (first (funcs op)) (second (funcs op)) stack))
- (error (str op " doesn't exist")))))))
- (defn ^:export evalrpnstring [st]
- (string/join " " (crawler (string/split st #"\s") '())))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement