Skip to content

Instantly share code, notes, and snippets.

@timmyshen
Last active August 16, 2018 14:31
Show Gist options
  • Save timmyshen/6958600 to your computer and use it in GitHub Desktop.
Save timmyshen/6958600 to your computer and use it in GitHub Desktop.
Write a function number_before_reaching_sum that takes an int called sum, which you can assume is positive, and an int list, which you can assume contains all positive numbers, and returns an int. You should return an int n such that the rst n elements of the list add to less than sum, but the rst n + 1 elements of the list add to sum or more. A…
fun number_before_reaching_sum (sum : int, xs : int list) =
if null xs then 0
(*else if null (tl xs) then 1*)
else if hd xs > sum then 0
else
let fun helper (i : int, partial_sum : int, tl_xs : int list) =
if partial_sum < 0 then i
else
helper(i + 1, partial_sum - hd tl_xs, tl tl_xs)
in
helper(1, sum, xs)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment