简体   繁体   中英

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM