如何不使用 compare_length_with

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

我有这段代码,但我不明白其中的意思。compare_length_with 函数,所以我想重写这段代码而不使用这个函数。

let rec blast list =
  let cmp = List.compare_length_with list 2 in
  if cmp = 0 then
    List.hd list
  else if cmp > 0 then
    blast (List.tl list)
  else
    failwith "not"

我看了

compare_length_with l n 相当于 compare (length l) n

但我很难让它工作。

ocaml
1个回答
0
投票

列表中的 List.compare_length_with 将列表长度与提供的数字进行比较。与其他任何 compare 函数,它是一个三值比较,立即告诉您两个比较值中的一个是小于、等于还是大于另一个。比如说 compare 0 1-1compare 1 10最后 compare 1 01. 该 List.compare_length_with 函数将 list 作为第一个参数,并使用常规比较函数将其长度与第二个参数进行比较。这里没有什么花哨的东西。 使用正则比较运算符(<, >, <=等),你可以获得同样的信息,但需要你做一些比较和ifthenelse表达式。这些都是很好的知识,但对于你的任务来说完全不是必需的,在你的任务中,你当然可以使用正则比较。例如:, List.length xs = 2 将为真,当 xs 包含两个元素,所以下面将返回倒数第二位的数字。

(* you will be get the least possible grade for such function *)
let rec bad_penultimate xs = 
   if List.length xs = 2 then List.hd xs 
   else bad_penultimate (List.tl xs)

这个函数相当不直观,运行时间为二次方,即对于一个长度为N的列表,它将进行O(N^2)个列表元素遍历。它做的事情也和你的 bforelast 但更简洁一些。

为了写出一个更好的函数,我们将使用模式匹配,并注意到长度为2的列表将始终与模式匹配 [_ ; _] 而为了了解一个列表是否有2个元素,我们不需要通过整个列表来计算其全长。我把它留给你作为一个练习,来设计一个好的倒数第二个函数。提示,不得有任何 List 中的模块函数,甚至没有ifthenelse表达式。试着只用模式匹配来做。

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