How to resolve the algorithm Optional parameters step by step in the OCaml programming language
How to resolve the algorithm Optional parameters step by step in the OCaml programming language
Table of Contents
Problem Statement
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Optional parameters step by step in the OCaml programming language
Source code in the ocaml programming language
let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table =
let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in
List.sort cmp table
# let data = [["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]];;
val data : string list list =
[["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]]
# sort_table data;;
- : string list list =
[[""; "q"; "z"]; ["a"; "b"; "c"]; ["zap"; "zip"; "Zot"]]
# sort_table ~column:2 data;;
- : string list list =
[["zap"; "zip"; "Zot"]; ["a"; "b"; "c"]; [""; "q"; "z"]]
# sort_table ~column:1 data;;
- : string list list =
[["a"; "b"; "c"]; [""; "q"; "z"]; ["zap"; "zip"; "Zot"]]
# sort_table ~column:1 ~reverse:true data;;
- : string list list =
[["zap"; "zip"; "Zot"]; [""; "q"; "z"]; ["a"; "b"; "c"]]
# sort_table ~ordering:(fun a b -> compare (String.length b) (String.length a)) data;;
- : string list list =
[["zap"; "zip"; "Zot"]; ["a"; "b"; "c"]; [""; "q"; "z"]]
You may also check:How to resolve the algorithm 100 prisoners step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Polymorphic copy step by step in the Nim programming language
You may also check:How to resolve the algorithm Pointers and references step by step in the Go programming language
You may also check:How to resolve the algorithm Munchausen numbers step by step in the Rust programming language
You may also check:How to resolve the algorithm Guess the number step by step in the Plain TeX programming language