写一个函数`smallest_absent t`,返回`l`中不存在的最小自然整数

问题描述 投票:0回答:2

写一个签名函数smallest_absent : int_list -> int,如调用smaller_absent l返回l中不存在的最小自然整数

let smallest_absent l =
match l with
|[] -> 0
|_ -> let m = ref (0,false) in
        while !m.(1) = false do
        if (mem l m.(0)) then !m.(1) := true ;
        else incr(m.(0));
        done;
    !m.(0);;

错误:

> while !m.(1) = false do
this expression is of type int * bool, but is used with the type 'a vect>`

我想知道我的代码有什么问题。如果它在概念上是正确的。谢谢。

compiler-errors ocaml
2个回答
2
投票

类型错误说明了一切:你正试图在_.(1)int的元组上使用向量查找bool

你正在寻找的功能是snd : 'a * 'b -> 'b

同样地,你应该用m.(0)fst !m而不是写fst : 'a * 'b -> 'a


4
投票

你已经有了答案,所以更像是评论或建议。

也许在概念上它是正确的,但它有一个可怕的复杂性,在ocaml程序中看到循环总是很痛苦(特别是在如此简单的程序中)。我建议你在递归方面考虑更多。

使用排序列表(没有重复)更简单,在这种情况下,你只需要找到i的第一个l[i] != i

let smallest_absent l =
  let l = List.sort_uniq compare l in
  let rec f i = function
    | [] -> i
    | h::t -> if h = i then f (i + 1) t
              else i in
  f 0 l

你可以想象进一步的优化。

© www.soinside.com 2019 - 2024. All rights reserved.