hs - tail recursion

This commit is contained in:
nihonium 2023-02-12 00:58:19 +03:00
parent c01cac4da2
commit ae316f42fe
Signed by: nihonium
GPG key ID: 0251623741027CFC

19
seminar01/Factorial.hs Normal file
View file

@ -0,0 +1,19 @@
module Main where
factorial :: Integer -> Either String Integer
factorial n = if n < 0 then
Left "n cannot be negative"
else Right $ factorial' n 1 where
factorial' 0 res = res
factorial' n res = factorial' (n - 1) $ n * res
main :: IO()
main = do
s <- getLine
let n = (read s :: Integer)
let res = factorial n
case res of
Right r -> do
print r
Left err -> do
putStrLn $ "Error: " ++ err