使用排序后返回 5 元组的中位数

Returning the median of a 5-tuple after using sort

我是 FP 和 OCaml 的新手。我之所以尝试以这种粗暴的方式进行操作,是因为我还没有学习 OCaml 中的列表。我正在尝试编写一个函数,在通过我编写的名为 sort5 的函数对 5 元组进行排序后,该函数 returns 5 元组的中值。这是代码

let median5 (a, b, c, d, e) =
let sort5 (a, b, c, d, e) = 
let sort2 (a, b) = if a > b then (b, a) else (a, b) in
let sort3 (a, b, c) = 
let (a, b) = sort2 (a, b) in
let (b, c) = sort2 (b, c) in
let (a, b) = sort2 (a, b) in
(a, b, c) in
let sort4 (a, b, c, d) = 
let (a, b) = sort2 (a, b) in 
let (b, c) = sort2 (b, c) in
let (c, d) = sort2 (c, d) in
let (a, b, c) = sort3 (a, b, c) in
(a, b, c, d) in
let (a, b) = sort2 (a, b) in 
let (b, c) = sort2 (b, c) in
let (c, d) = sort2 (c, d) in
let (d, e) = sort2 (d, e) in
let (a, b, c, d) = sort4 (a, b, c, d) in
(a, b, c, d, e);;

我尝试使用 if, get_med (a, b, c, d, e) = c 和其他一些我认为可行但一无所获的愚蠢方法。我总是遇到语法错误,如果我设法摆脱它,那么我就会陷入未使用的变量 sort5 或 get_med。我已经为这种粗暴行为感到抱歉。谢谢。

将以下内容添加到代码末尾:

in
let (_, _, m, _, _) = sort5 (a, b, c, d, e) in
m

如果您单独定义每个函数,您的代码将更具可读性。

let sort2 (a, b) =
  if a > b then (b, a) else (a, b)

let sort3 (a, b, c) = 
  let (a, b) = sort2 (a, b) in
  let (b, c) = sort2 (b, c) in
  let (a, b) = sort2 (a, b) in
  (a, b, c)

let sort4 (a, b, c, d) = 
  let (a, b) = sort2 (a, b) in 
  let (b, c) = sort2 (b, c) in
  let (c, d) = sort2 (c, d) in
  let (a, b, c) = sort3 (a, b, c) in
  (a, b, c, d)

let sort5 (a, b, c, d, e) =
  let (a, b) = sort2 (a, b) in 
  let (b, c) = sort2 (b, c) in
  let (c, d) = sort2 (c, d) in
  let (d, e) = sort2 (d, e) in
  let (a, b, c, d) = sort4 (a, b, c, d) in
  (a, b, c, d, e)

let median5 (a, b, c, d, e) =
  let (_, _, m, _, _) = sort5 (a, b, c, d, e) in
  m

正如您所说,这段代码根本不实用。我希望你能尽快学会使用列表:-)