diff options
author | Teddy Wing | 2017-08-20 12:42:28 +0200 |
---|---|---|
committer | Teddy Wing | 2017-08-20 15:11:52 +0200 |
commit | e94543c1b42bac8928aa8bf4fa3341563f7631b8 (patch) | |
tree | 0cb05e9e02b85f7031884c60ccc23a4e05e37049 /src | |
parent | 5aecb2aede18f285a9cce3a0fb066a1911814a17 (diff) | |
download | sorbot-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')
-rw-r--r-- | src/Plugin/Factorial.hs | 29 | ||||
-rw-r--r-- | src/PluginList.hs | 4 |
2 files changed, 32 insertions, 1 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] 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 ] |