From e94543c1b42bac8928aa8bf4fa3341563f7631b8 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 20 Aug 2017 12:42:28 +0200 Subject: 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. --- src/Plugin/Factorial.hs | 29 +++++++++++++++++++++++++++++ src/PluginList.hs | 4 +++- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/Plugin/Factorial.hs (limited to 'src') 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 = "!" + , description = "Calculate the factorial of " + } + +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] diff --git a/src/PluginList.hs b/src/PluginList.hs index bfcae7e..7c950c0 100644 --- a/src/PluginList.hs +++ b/src/PluginList.hs @@ -3,6 +3,7 @@ module PluginList ) where import Plugin.Base (Plugin) +import Plugin.Factorial import Plugin.GitHubCommit import Plugin.GitRemoteSetOrigin @@ -10,6 +11,7 @@ import Plugin.GitRemoteSetOrigin -- cause a circular import. plugins :: [Plugin] plugins = - [ gitHubCommit + [ factorial + , gitHubCommit , gitRemoteSetOrigin ] -- cgit v1.2.3