{- |
Description: Tutorial for solving problems
Copyright: Copyright (C) 2023 Yoo Chung
License: GPL-3.0-or-later
Maintainer: dev@chungyc.org

Some solutions to "Problems.Tutorial".
-}
module Solutions.Tutorial (sumNumbers, sumNumbers', sumNumbers'') where

-- | Add numbers from 1 to a given number @n@.
sumNumbers :: Integer -> Integer
sumNumbers :: Integer -> Integer
sumNumbers Integer
0 = Integer
0
sumNumbers Integer
n = Integer
n Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer -> Integer
sumNumbers (Integer
nInteger -> Integer -> Integer
forall a. Num a => a -> a -> a
-Integer
1)

-- | Add numbers from 1 to a given number @n@.
--
-- Accumulates the sum with a tail recursive function.
sumNumbers' :: Integer -> Integer
sumNumbers' :: Integer -> Integer
sumNumbers' Integer
n | Integer
n Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
0 = Integer -> Integer -> Integer
forall {t}. (Eq t, Num t) => t -> t -> t
add Integer
0 Integer
n
              | Bool
otherwise = Integer
0
  where add :: t -> t -> t
add t
s t
0 = t
s
        add t
s t
m = t -> t -> t
add (t
st -> t -> t
forall a. Num a => a -> a -> a
+t
m) (t
mt -> t -> t
forall a. Num a => a -> a -> a
-t
1)

-- | Add numbers from 1 to a given number @n@.
--
-- Computes \( \frac{n (n+1)}{2} \).
sumNumbers'' :: Integer -> Integer
sumNumbers'' :: Integer -> Integer
sumNumbers'' Integer
n | Integer
n Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
0 = Integer
n Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Integer
nInteger -> Integer -> Integer
forall a. Num a => a -> a -> a
+Integer
1) Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`div` Integer
2
               | Bool
otherwise = Integer
0