Create New List with Cumulative Sum
I am trying to solve this problem
Exercise 8.3 Write a function that takes a list of numbers and returns the
cumulative sum; that is, a new list where the ith element is the sum of
the first i + 1 elements from the original list. For example, the
cumulative sum of [1, 2, 3] is [1, 3, 6].
I have written this code which according to me is correct.
let lastItem = function
| [] -> 0
| l -> List.hd (List.rev l);;
let rec cumulativeSumActual accum input =
match input with
| [] -> accum
| hd::tl -> cumulativeSumActual (accum::[(lastItem accum) + hd]) tl;;
let cumulativeSum = cumulativeSumActual [];;
let output = cumulativeSum [1; 2; 3;];;
let printer item =
print_int item
print_string "\n";;
List.iter printer output
But I get the error
user1@ubuntu:~/Documents/Programs$ ocamlc -o CumulativeList
CumulativeList.ml File "CumulativeList.ml", line 8, characters 33-38:
Error: This expression has type 'a list but an expression was expected of
type 'a
No comments:
Post a Comment