I'm working on an assignment to calculate the sum of all integers in a list. I am supposed to do so without help from any standard library functions other than the standard addition operator.
I assume this means I cannot use length. I'm understanding that correct, right? This becomes and issue as I'm not sure how I'd know when to stop my recursive function to iterate through the array.
The input's a should be expected to deal with are [] and [0-X] where x is any integer. The example has X as 10, so don't expect anything huge to be tested.
The assignment mentioned it should be in the following format, but I'm not sure I follow:
sum1 [] = ...
sum1 (x:xs) = ...
Here's what I have utilizing length. It works correctly, and I don't really care if it's inefficient. It's my first time using Haskell:
iterate_list :: [Int] -> Int -> Int -> IO()
iterate_list func_list index total = do
if index < length func_list
then do
let new_total = total + (func_list !! index)
let new_index = index + 1
iterate_list func_list new_index new_total
else
print(total)
sum1 :: [Int] -> IO()
sum1 list = do
if length list < 1
then do
print(0)
else
iterate_list list 0 0
update: Based on comments, here is the code I've produced.
total :: Int
total = 0
sum1 :: [Int] -> IO()
sum1 (x:xs) = do
if xs == []
then do
print(total)
else do
let total = total + x
sum1 xs
However, the issue I'm having now is total returns 0, almost like it's a constant. I might be programming it that way, but I'm not too sure what's going on.
Based on the assignment description, I cannot pass a variable through the recursive function to store this value. I've done it that way before. Does anyone know if there is a way to have a "total" variable outside of the function.