是否有一个 OCaml 函数用于确定一个整数列表中的每个元素是否按顺序排列?

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

例如,我希望列表[1;2;3;4]返回true,但[1;3;4;5]不是。

到目前为止,我已经试过了。我相信根据我的测试用例,这样做是可行的......但如果有人有反馈或建议,那就太好了。基本上,我不确定如何使用内置的列表库来实现它,我知道它的运行效率比硬编码的努力更有效。可以用fold_left或fold_right实现吗?

let is_seq elt1 elt2 =
  if elt2 - elt1 = 1 then true else false

let next_elem lst = 
  match lst with 
  | [] -> failwith "this should not happen"
  | h :: t -> h

(**[is_sequential lst] returns true if the list is sequential and 
   false if it is not *)
let rec is_sequential lst =
  match lst with
  | [] -> true
  | h :: [] -> true
  | h :: t -> if is_seq h (next_elem t) then is_sequential t else false

list ocaml sequential
1个回答
0
投票

我不知道你是如何处理int溢出的。

let rec is_seq lst =
  match lst with
  | [] -> true
  | hd::[] -> true
  | hd1::hd2::tl when hd1 = Int.max_int -> failwith "Int too large to continue"
  | hd1::hd2::tl when (succ hd1) = hd2 -> is_sorted (hd2::tl)
  | _ -> false

0
投票

所以我对fold_left的建议是有一个包含之前遇到的整数的累加器。

let is_sequential l = 
  match l with 
  | [] -> true 
  | x::xs -> 
     List.fold_left (fun (is_seq,prev_e) e -> (e = prev_x + 1 && is_seq,e)) (true,x) xs

你也可以用异常来停止is_seq变成false的时候...

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