Skip to content

Instantly share code, notes, and snippets.

@Lysxia Lysxia/Func.hs
Created Oct 8, 2019

Embed
What would you like to do?
data FuncResult = Ok Integer | NameErr | ArityErr Integer
resultOf :: String -> [Integer] -> FuncResult
resultOf = applyFuncs
[ Func ["D", "derangement", "derangements"] (Arity1 (\n -> derangementR !! fromInteger n))
, Func ["!", "factorial"] (Arity1 factorial)
, Func ["g", "gcd", "euclidean"] (Arity2 gcd)
, Func ["p", "P", "partition"] (Arity2 partition)
, Func ["s", "S", "sterling"] (Arity2 sterling)
, Func ["c", "C", "ncr", "combinations"] (Arity2 ncr)
]
data Func
= Func
[String] -- names
FuncBody -- function definition
data FuncBody
= Arity1 (Integer -> Integer)
| Arity2 (Integer -> Integer -> Integer)
arity :: FuncBody -> Integer
arity (Arity1 _) = 1
arity (Arity2 _) = 2
applyFunc :: Func -> String -> [Integer] -> FuncResult
applyFunc (Func names body) n args
| n `elem` names = case (body, args) of
(Arity1 f, [n]) -> Ok (f n)
(Arity2 f, [n, k]) -> Ok (f n k)
(body, _) -> ArityErr (arity body)
| otherwise = NameErr
-- for foldMap
instance Semigroup FuncResult where
Ok i <> _ = Ok i
ArityErr i <> _ = ArityErr i
NameErr <> j = j
instance Monoid FuncResult where
mempty = NameErr
applyFuncs :: [Func] -> String -> [Integer] -> FuncResult
applyFuncs = foldMap applyFunc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.