简体   繁体   English

OCaml:表示整数列表的简单赋值

[英]OCaml: simple assignment to represent a list of ints

Hello I am learning the OCaml language and working on an assignment.您好,我正在学习 OCaml 语言并完成一项任务。

infinite precision natural numbers can be represented as lists of ints between 0 and 9无限精度自然数可以表示为 0 到 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.编写一个 function ,它采用 integer 并用 0 到 9 之间的整数列表表示它,其中列表的头部包含最低有效数字,列表的最后一个元素表示最高有效数字。 If the input is negative return None.如果输入为负,则返回 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.我在第 4 行遇到语法错误。由于我是这种语言的新手,所以无法弄清问题所在。 Can somebody please help on this.有人可以帮忙吗?

The in keyword must go with a let . in关键字必须是 go 和let You could use a local function aux , as follows:您可以使用本地 function aux ,如下所示:

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.这不符合您的要求,但语法和类型是有效的,我相信您可以修复 rest。

Vicky, you forgot to define acc and also forgot to put else if statement. Vicky,你忘了定义acc也忘了加上else if语句。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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