Sha256: f74faab08f336c93aaabbf8731659a451496e3dd68feb6e9ad6e3627a725a4b0
Contents?: true
Size: 873 Bytes
Versions: 396
Compression:
Stored size: 873 Bytes
Contents
(ns wordy (:require [clojure.string :refer [join]])) (def ^:private ops {"plus" + "minus" - "multiplied by" * "divided by" /}) (def ^:private tokens-pattern (re-pattern (str (join "|" (keys ops)) "|-?\\d+|\\S+"))) (defn- parse-op [op-str] (or (ops op-str) (throw (IllegalArgumentException. (str "unknown operator " op-str))))) (defn evaluate [expr] (if-let [[_ exprs] (re-matches #"What is (.+)\?" expr)] (if-let [[token & tokens] (re-seq tokens-pattern exprs)] (reduce (fn [acc [op x]] ((parse-op op) acc (Integer/parseInt x))) (Integer/parseInt token) (partition-all 2 tokens)) (throw (IllegalArgumentException. "no arithmetic expression found"))) (throw (IllegalArgumentException. "cannot recognize question"))))
Version data entries
396 entries across 396 versions & 1 rubygems