Search code examples
sortingocamlmedian

Returning the median of a 5-tuple after using sort


I am new to FP and OCaml. The reason I am trying to do it in such a brute way is because I haven't learned lists in OCaml. I am trying to write a function which returns the median of a 5-tuple after sorting the 5-tuple by a function called sort5 which I wrote. This is the code

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);;

I tried using if, get_med (a, b, c, d, e) = c and bunch of other silly ways that I thought would work but got nothing. I always get a syntax error, if I manage to get rid of that then I am stuck with unused variable sort5 or get_med. I am already sorry about the bruteness. Thank you.


Solution

  • Add the following to the end of your code:

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

    Your code will be a lot more readable if you define each function on its own.

    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
    

    As you say, this code isn't at all practical. I hope you'll learn to work with lists soon :-)