Ocaml 如何从一个列表中生成非递减列表?不使用递归,使用左/右折叠。奥卡姆

Ocaml 如何从一个列表中生成非递减列表?不使用递归,使用左/右折叠。奥卡姆,ocaml,foldleft,Ocaml,Foldleft,这是我对这个问题的看法,但我不能正确地键入fold\u left方法 例如: nonDecreasing[1;4;3;2;5;6] == [[1;4];[3];[2;5;6]] 让不减损列表= 匹配列表 |[]->帮助(a、b、c)=b |h::[]->2(*我不知道,“2”只用于编译*) |h::t->let help=List.fold_left(fun(prev,lFinal,lTemp)h->if(h要使用fold构建列表,使用fold_right可能更容易,因为您只能有效地将元素预

这是我对这个问题的看法,但我不能正确地键入
fold\u left
方法

例如:

nonDecreasing[1;4;3;2;5;6] == [[1;4];[3];[2;5;6]] 
让不减损列表=
匹配列表
|[]->帮助(a、b、c)=b
|h::[]->2(*我不知道,“2”只用于编译*)

|h::t->let help=List.fold_left(fun(prev,lFinal,lTemp)h->if(h要使用fold构建列表,使用
fold_right
可能更容易,因为您只能有效地将元素预先添加到列表中,因此您应该从右侧开始构建列表,这就是
fold_right
所做的。(您也可以使用
fold_left
,但需要在附加步骤中反转列表或使用昂贵的列表串联。)

使用
折叠右键构建列表的一个更简单的示例是,从列表的末尾开始构建列表元素总和的列表,例如,
总和[A;b;c]
给出
[A+b+c;b+c;c]
。代码如下所示

let sums = List.fold_right
  (fun x ys ->
    match ys with
      | [] -> [x]
      | hd :: tl -> (x + hd) :: ys)
  [1; 2; 3; 4; 5]
  []
let non_decreasing xs =
  List.fold_right
    (fun x outer ->
      match outer with
      | [] -> [[x]]
      | outer_hd :: outer_tl ->
          if x <= List.hd outer_hd then
            (x :: outer_hd) :: outer_tl
          else
            [x] :: outer)
    xs
    []
内部函数所做的是获取已构建列表的第一个元素并将其添加到当前元素(请记住,这些元素是从右向左访问的)。然后将总和添加到已存在列表的前面

定义
non_decresing
函数的工作方式与此类似。但是,我们必须使用嵌套列表,这使得事情更加复杂。代码如下

let sums = List.fold_right
  (fun x ys ->
    match ys with
      | [] -> [x]
      | hd :: tl -> (x + hd) :: ys)
  [1; 2; 3; 4; 5]
  []
let non_decreasing xs =
  List.fold_right
    (fun x outer ->
      match outer with
      | [] -> [[x]]
      | outer_hd :: outer_tl ->
          if x <= List.hd outer_hd then
            (x :: outer_hd) :: outer_tl
          else
            [x] :: outer)
    xs
    []
让非_递减xs=
List.fold\u right
(乐趣x外部->
外配
|[]->[[x]]
|外部高清::外部高清->

如果你能解释一下你的代码在做什么,你在努力解决什么具体问题,最好也能格式化你的代码,使其在一个屏幕上都可见。如果你让我们更容易理解你的实际问题,你就更有可能得到一个好的答案。