I have a problem in which I am asked for a function that sums all the elements in a given variable x. For instance, sum([5,5,5]) should return 15.
My troubles come into play when I test the sum of a single integer like this: sum(5)
The function is supposed to be able to go back and fourth between single numbers and a list of numbers. I know that to do this, I need a datatype which has some Int of int | Null | ...
My question is how do I make the code below work for the test case sum(5);
fun sum(x) = if x = nil
then 0
else hd(x) + sum(tl(x))
val result = sum([5,5]);
I think I need something like:
else if (int? x) then x
else hd(x) + sum(tl(x))
but when i do this with my datatypes i get clash of int vs int list.
sum (Int 5)orsum Null, notsum [5,5,5]. Please expand on what the function is supposed to do. - molbdnilo