0
votes

I am new to OCaml and am writing a recursive program in OCaml which returns the n-th element of a list. However I need to display an informative error message, displaying a list, when the list is too short, like "( a b c ) does not have 5 elements". Here's my code

    let rec nth_element n list =
       match list with
       | [] -> raise(Failure "")
       | a :: l -> match n with
              0 -> a
              n -> nth_element (n-1) l

I want to replace the 'raise(Failure "")' part with the required error message. Writing a function for the same didn't help as it returned the unit type whereas the int type is required.

2

2 Answers

2
votes

Do you need to print the entire list in the error message? If you only need to print the missing item count you could do it like this:

failwith (Printf.sprintf "The list is %d elements too short" n)
1
votes

Anywhere you have an expression e in OCaml you can also have an expression s; e where s is an expression of type unit. Here's a function that just raises an exception:

let f () = raise (Failure "")

Here's a function that does the same, but writes out a message first:

let f () = Printf.printf "helpful message"; raise (Failure "")

As a side comment, this isn't particularly idiomatic OCaml. Why not put the helpful message inside the exception? Like this:

let f () = raise (Failure "helpful message")