Skip to content

Instantly share code, notes, and snippets.

@viebel
Created November 14, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viebel/4b922d2ce6ec9df6ce541b3055116ece to your computer and use it in GitHub Desktop.
Save viebel/4b922d2ce6ec9df6ce541b3055116ece to your computer and use it in GitHub Desktop.
text rules matching
(ns my.chat
(:require [clojure.string :as str]))
(def rules
[["hello" "hello you"]
["bye" "see you soon"]
["my name is Riccardo" "nice to meet you Riccardo"]])
(defn respond-fixed [input]
(or (second (first (filter (fn [[in out]]
(= in input))
rules)))
"please say it again"))
[(respond-fixed "bye")
(respond-fixed "my name is Riccardo")
(respond-fixed "my name is Frank")
(respond-fixed "i am happy")]
(def rules-loose
[["hello" "hello you"]
["bye" "see you soon"]
["my name is" "nice to meet you anonymous"]])
(defn respond-loose [input]
(or (second (first (filter (fn [[in out]]
(str/includes? input in))
rules-loose)))
"please say it again"))
[(respond-loose "bye")
(respond-loose "my name is Riccardo")
(respond-loose "my name is Frank")
(respond-loose "i am happy")]
(def rules-smart
[[#"hello (.*)" "nice to meet you "]
[#"bye (.*)" "see you soon "]])
(defn match-rule [in [pattern out]]
(when-let [[_ dyn] (re-matches pattern in)]
(str out dyn)))
(defn respond-smart [input]
(or (some (partial match-rule input)
rules-smart)
"please say it again"))
[(respond-smart "hello Riccardo")
(respond-smart "hello Franck")
(respond-smart "bye Franck")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment