DEV Community

Discussion on: Challenge: Get Closest Number in an Array

Collapse
 
modaf profile image
Modaf

OCaml with list instead of array

let rec closest num list = match list with
[] -> failwith "Empty list"
|[n] -> n
|h :: q ->
    let closest_q = closest num q in
    let val_h = abs (num - h) in
    let val_q = abs (num - closest_q) in
    if (val_h < val_q) then h else closest_q;;