JamesPD
JamesPD

Reputation: 620

Circular reference functions in OCaml

Lets say I wish to create an OCaml program which takes a list of integers and creates the sum of double the first item, triple the second item, double the third item, and so on..

let rec doubler some_list =
  match some_list with
  | [] -> 0;
  | head::tail -> (head * 2) + (tripler tail);;
                               
let rec tripler some_list =
  match some_list with
  | [] -> 0;
  | head::tail -> (head * 3) + (doubler tail);;

let maths_stuff some_list =
  doubler some_list;;

let foo = maths_stuff [1;2;3;4;5;6] (* Should be 54 *)

Currently I get a Error: Unbound value tripler error because OCaml doesn't know what it is, but I can't reorder the two functions without having the same problem with doubler.

Whats the syntax for specifying a circular dependency between two functions? All I've found with Google is discussions of circular dependencies between modules during the build process, which isn't what I'm after.

Many TIA

Upvotes: 0

Views: 268

Answers (1)

octachron
octachron

Reputation: 18912

Mutually recursive items (values, types, classes, classes types, modules) need to be grouped with and:

let rec doubler = function
  | [] -> 0;
  | head::tail -> head * 2 + tripler tail
                              
and tripler = function
  | [] -> 0;
  | head::tail -> head * 3 + doubler tail

Upvotes: 2

Related Questions