返回输入变量上特定索引上具有最高编号的列表 - 列表列表

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

这里是新手! 我正在尝试构建一个程序,该程序返回特定索引上具有最高数字的列表。我已经尝试了很多事情,这看起来是我能想到的最简单的代码。

在下面的示例中,我期望返回列表

["2";"4";"6";"7";"8";"4"]
。但是我遇到了这个错误:

File "blablabla.ml", line 7, characters 63-74:
Error: This expression has type int but an expression was expected of type 'a list

有人可以帮忙吗?

let a = [
  ["1";"2";"3";"4";"5";"6"];
  ["2";"5";"6";"1";"5";"7"];
  ["1";"2";"3";"4";"5";"6"];
  ["2";"4";"6";"7";"8";"4"]
];;

let rec max lista i = match lista with
  | [] -> 0
  | x::xs ->
      let best_list = max xs i in
      if int_of_string (List.nth x i) > int_of_string (List.nth best_list i) then 
        x
      else
        best_list
;;

let result = max a 4;;

result;;

编辑: 仍然没有成功,感谢@G4143和@glennsl,我设法采用另一种方法,但知道正在抱怨语法错误。

let max l i = match l with
  | [] -> []
  | x::xs ->
      let rec compare_lists x xs i =
        if i < (List.length xs) then
          if (List.nth x i) > (List.nth xs i) then
            x
          else
            xs
        else
          failwith "Position too large for list"
;;
ocaml
2个回答
0
投票

这就是我解决这个问题的方法。注意:我遗漏了许多列表分支的解决方案。

let get_max_at_pos l1 l2 pos =
  if (pos < List.length l1) && (pos < List.length l2)
  then
    if (List.nth l1 pos) < (List.nth l2 pos)
    then
      l2
    else
      l1
  else
    failwith "Position too large for list"

let get_max l pos =
  match l with
  | [] -> None
  | hd::[] -> Some hd(*should check position against hd length*)
  | hd1::hd2::[] -> Some (get_max_at_pos hd1 hd2 pos)
  | hd::tl -> (*now you have to solve the branch for many lists*)

这是一个更好、更干净的解决方案,因为你现在已经可以使用它了:

let a =
  [
    [1; 2; 3; 4; 5; 6];
    [2; 5; 6; 1; 5; 7];
    [1; 2; 3; 4; 5; 6];
    [2; 4; 6; 7; 8; 4]
  ]

let get_max_of_pos l1 l2 pos =
  if (pos < List.length l1) && (pos < List.length l2)
  then
    if (List.nth l1 pos) < (List.nth l2 pos)
    then
      l2
    else
      l1
  else
    failwith "List too short"

let get_max l pos =
  match l with
  | [] -> failwith "Empty list of list"
  | hd::tl ->
    List.fold_left (fun a d -> get_max_of_pos a d pos) hd tl

let ans = get_max a 5

如果愿意,您可以手动重写fold_left部分。


0
投票

您是否尝试过将问题分解为更简单的步骤?如何创建一个函数,它接受 2 个长度相等的列表,并按位置返回一个包含两个列表中最高元素的列表。像这样的东西。

let rec get_max_at_position l1 l2 pos =
  if pos < (List.length l1)
  then
    if (List.nth l1 pos) > (List.nth l2 pos)
    then
      l1
    else
      l2
  else
    failwith "Position too large for list"
© www.soinside.com 2019 - 2024. All rights reserved.