返回中值的函数?(OCaml)

返回中值的函数?(OCaml),ocaml,median,Ocaml,Median,在OCaml中,如何编写一个接受5个参数并返回中值的中值函数。例如,med5 2 5 7 4 3将返回4 我使用if和else语句编写了一个med3函数(返回3个参数的中间值),但如果我尝试对5个参数使用相同的技术,这将是非常复杂的:( 让med3 a b c= 如果((b=a)|(c=a))那么a else如果((a=b)|(c=b))那么b else c;; 对于med5函数,我希望能够使用min和max函数(内置于OCaml中)放弃5个参数中的最高值和最低值。然后我可以使用我已经编写的m

在OCaml中,如何编写一个接受5个参数并返回中值的中值函数。例如,
med5 2 5 7 4 3
将返回4

我使用if和else语句编写了一个med3函数(返回3个参数的中间值),但如果我尝试对5个参数使用相同的技术,这将是非常复杂的:(

让med3 a b c=
如果((b=a)|(c=a))那么a
else如果((a=b)|(c=b))那么b else c;;
对于med5函数,我希望能够使用min和max函数(内置于OCaml中)放弃5个参数中的最高值和最低值。然后我可以使用我已经编写的med3函数返回其余3个参数的中值,但是如何放弃最小值和最大值


任何帮助都将不胜感激:)

您可以将这5个参数放入一个列表中,然后从列表中删除一个元素就很容易了。

如果您可以使用
Array
,那么只需将5个条目放入一个数组中,对其进行排序,然后返回
a[2]
。如果您的作业中也禁止使用,您可以使用穷人气泡排序选择最大值,然后选择最小值:

let med5 a b c d e =
  (* move the max towards 'e' *)
  let a,b = if a<=b then a,b else b,a in
  let b,c = if b<=c then b,c else c,b in
  ...
  (* then move the min towards 'd', don't forget to reverse the comparisons *)
  ...
  in med3 a b c
让med5 a b c d e=
(*将最大值移向“e”*)

设a,b=如果a禁止列表和数组,则可以使用三个变量存储五个元素中最大的三个元素:

let med5 a b c d e =
    let first  = ref min_int in
    let second = ref min_int in
    let third  = ref min_int in

    if      a >= !first  then (third := !second; second := !first; first := a)
    else if a >= !second then (third := !second; second := a)
    else if a >= !third  then (third := a);

    if      b >= !first  then (third := !second; second := !first; first := b)
    else if b >= !second then (third := !second; second := b)
    else if b >= !third  then (third := b);

    (* you guess what to do for c, d, e ;-) *)

    (* return the third largest element: *)
    !third

不幸的是,我的问题是一项作业的一部分,该作业规定我们不能使用列表,因为我们还不应该了解它们:(我也不知道如何使用列表编写函数!!!:'(我还应该提到,这项任务的截止日期已经过去了。除非我弄错了,
med5 2 5 7 4 3
4
而不是
3
哈哈,你完全正确,谢谢你指出:)
let med5 a b c d e =
    let first  = ref min_int in
    let second = ref min_int in
    let third  = ref min_int in

    if      a >= !first  then (third := !second; second := !first; first := a)
    else if a >= !second then (third := !second; second := a)
    else if a >= !third  then (third := a);

    if      b >= !first  then (third := !second; second := !first; first := b)
    else if b >= !second then (third := !second; second := b)
    else if b >= !third  then (third := b);

    (* you guess what to do for c, d, e ;-) *)

    (* return the third largest element: *)
    !third