ocamlocamlbuildocamlyacc

OCaml: simple assignment to represent a list of ints


Hello I am learning the OCaml language and working on an assignment.

infinite precision natural numbers can be represented as lists of ints between 0 and 9

Write a function that takes an integer and represents it with a list of integers between 0 and 9 where the head of the list holds the least significant digit and the very last element of the list represents the most significant digit. If the input is negative return None. We provide you with some use cases:

For example:

toDec 1234 = Some [4; 3; 2; 1]

toDec 0 = Some []

toDec -1234 = None

I have written below code for it.

let rec toDec i = 
(
if i < 10 then i::[]  
else toDec ((i mod 10)::acc) (i/10) in toDec [] i;
);;

I am getting syntax error on line 4. Since I am new to this language, not able to get what's wrong. Can somebody please help on this.


Solution

  • The in keyword must go with a let. You could use a local function aux, as follows:

    let toDec i =
      let rec aux acc i = 
        if i < 10 then i::[]  
        else aux ((i mod 10)::acc) (i/10)
      in
      aux [] i
    

    This doesn't do what you want but syntax and types are valid and I'm sure you can fix the rest.