Ocaml Nested Functions

Can someone explain the syntax used for when you have nested functions?

For example I have a outer and an inner recursive function.

let rec func1 list = match list with
[] -> []
|(head::tail) ->
let rec func2 list2 = match list2 with
...
;;

I have spent all day trying to figure this out and I'm getting a ever tiring "Syntax error".

3

1 Answer

You don't show enough code for the error to be obvious.

Here is a working example:

# let f x =
      let g y = y * 5 in
      g (x + 1);;
val f : int -> int = <fun>
# f 14;;
- : int = 75

Update

Something that might help until you're used to OCaml syntax is to use lots of extra parentheses:

let rec f y x =
    match x with
    | h :: t -> (
        let incr v = if h = y then 1 + v else v in
        incr (f y t)
    )
    | _ -> (
        0
    )

It's particularly hard to nest one match inside another without doing this sort of thing. This may be your actual problem rather than nested functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest