0
votes

I have an OCaml function which I got from the post: List reversing in Ocaml

let rev_list l =
      let rec rev_acc acc = function
        | [] -> acc
        | hd::tl -> rev_acc (hd::acc) tl
      in 
      rev_acc [] l

I tested this, and it obviously worked, but I don't understand why. Inside the main function, when defining rev_acc, it says that it only takes on argument acc. However, when then call the function with two parameters. Why are we allowed to do this?

Also, why do we say let rec rev_acc acc = function, what does the "= function" mean, and why aren't we using a match? I'm assuming this has to do with not having to specify certain arguments; I do remember something about that in the last part of the course, which was only briefly covered. Does it have anything to do with currying?

Sorry if these are stupid questions; I'm rather new to functional programming, if that wasn't already obvious.

Any help is greatly appreciated. Thanks.

2

2 Answers

5
votes

Ocaml has a special function syntax which takes an implicit argument and automatically inserts it into the match expressions to follow

The rev_acc function in your program is defined using function

let rec rev_acc acc = function
  | [] -> acc
  | hd::tl -> rev_acc (hd::acc) tl

This is equivalent to

let rec rev_acc acc xs =
  match xs with
    | [] -> acc
    | hd::tl -> rev_acc (hd::acc) tl 

Above, each version of rev_acc accepts two arguments

0
votes

You are right that rev_acc is a function that takes one argument. BUT it then returns a function taking another argument. So when you write

rev_acc [] l

what actually happens is

let unnamed_function = rev_acc []
in
unnamed_function l