用户定义类型的 OCaml 排序列表

OCaml sorting list of user-defined types

我有一个 cache 的列表,我需要按 hiddenDate 对它进行排序,例如“2007/07/20”(最近排在第一位)。如何仅使用 hiddenDate 参数在 Ocaml 中对这个列表进行排序?

type cache = {         
    code: string;      
    name: string;      
    state: string;      
    (...)
    hiddenDate: string; 
    (...) 
    altitude: int       
} ;;

val hiddenDateSort: cache list -> cache list

这是 sort 函数的文档:

val sort : ('a -> 'a -> int) -> 'a list -> 'a list 

Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, compare is a suitable comparison function. The resulting list is sorted in increasing order. List.sort is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space.

因此,您需要为隐藏日期字段提供比较功能。而且,你不能像字符串那样只比较日期。这将导致不正确的排序。第一个近似值如下:

let date str = Str.(split (regexp "/") str)
let compare_dates s1 s2 = compare (date s1) (date s2)
let compare_by_hidden_date c1 c2 = compare_dates c1.hiddenDate c2.hiddenDate
let sort_by_hidden_date = List.sort compare_by_hidden_date