In effort to study OCaml, I am going by way of some straightforward LeetCode issues and making an attempt to implement them. I arrive on the appropriate reply, however I am nonetheless creating an instinct for canonical OCaml code. I might respect any suggestions on my implementation.
As talked about, that is downside 1 on LeetCode. A fast abstract of the issue: given an array of integers, return the indices of the two numbers that sum to a given “goal”.
For instance, given
nums: [2, 7, 11, 15] and
goal: 13, the end result needs to be
[0, 2] (the integers at indices
2 sum to
Moreover, we are able to assume a novel answer exists for the given array and goal.
Right here is my refined try at implementing this in OCaml:
let two_sum nums goal = let rec aux i j = let n1 = Record.nth nums i in let n2 = Record.nth nums j in if n1 + n2 = goal then [i; j] else if j = (Record.size nums) - 1 then aux (i + 1) (i + 2) else aux i (j + 1) in aux Zero 1;;
I respect any suggestions.