Vicky
Vicky

Reputation: 25

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.

Upvotes: 0

Views: 282

Answers (2)

RaZzLe
RaZzLe

Reputation: 2128

Vicky, you forgot to define acc and also forgot to put else if statement.

Update your code as below,

let rec toDec ?acc:(acc=[]) i =
if i < 0 then None
else if i = 0 then Some acc
else toDec ~acc:((i mod 10)::acc) (i / 10)

Upvotes: 1

Martin Jambon
Martin Jambon

Reputation: 4949

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.

Upvotes: 1

Related Questions