aboutsummaryrefslogtreecommitdiffstats
path: root/src/Plugin
diff options
context:
space:
mode:
authorTeddy Wing2017-08-20 12:42:28 +0200
committerTeddy Wing2017-08-20 15:11:52 +0200
commite94543c1b42bac8928aa8bf4fa3341563f7631b8 (patch)
tree0cb05e9e02b85f7031884c60ccc23a4e05e37049 /src/Plugin
parent5aecb2aede18f285a9cce3a0fb066a1911814a17 (diff)
downloadsorbot-e94543c1b42bac8928aa8bf4fa3341563f7631b8.tar.bz2
Add Factorial plugin
This plugin calculates factorials. It's not super optimised, but works for small inputs. Adds the 'text-show' plugin to convert the resulting integer to a `Data.Text` to be returned by the plugin action. At first I had tried /^\d+!$/ for the regex match, but that produced this error: sorbot/src/Plugin/Factorial.hs:14:24: error: lexical error in string/character literal at character 'd' Tried to fix that by using /^\\d+!$/, but that didn't match anything. Then tried a long-form character class, /^[:digit:]+!$/, which TDFA implies it supports, but a quick look at the code seems to indicate that those parts were removed or commented out. Not sure what was going on with that. So instead went for the remaining solution, a `0-9` character class.
Diffstat (limited to 'src/Plugin')
-rw-r--r--src/Plugin/Factorial.hs29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/Plugin/Factorial.hs b/src/Plugin/Factorial.hs
new file mode 100644
index 0000000..f8cfee2
--- /dev/null
+++ b/src/Plugin/Factorial.hs
@@ -0,0 +1,29 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module Plugin.Factorial
+ ( factorial
+ ) where
+
+import Text.Regex.TDFA ((=~))
+import TextShow (showt)
+
+import qualified Message as M
+import Plugin.Base
+
+factorial = Plugin
+ { matchRegex = "^([0-9]+)!$"
+ , perform = factorialAction
+ , command = "<integer>!"
+ , description = "Calculate the factorial of <integer>"
+ }
+
+factorialAction :: PluginAction
+factorialAction message = do
+ case M.textStr message =~ matchRegex factorial :: [[String]] of
+ [] -> return $ Left "I didn't understand"
+ (m:_) -> do
+ let number = last m
+ return $ Right $ showt $ calculate $ (read number :: Int)
+
+calculate :: (Enum a, Num a) => a -> a
+calculate n = product [1..n]