どう書く?.orgに投稿した。
cf. データの整列
sort_by_dic が辞書順に整列する関数,sort_by_dis が距離の昇順に整列する関数。
type point = Point of float * float let compare_point a b = match (a, b) with (Point (x1, y1), Point (x2, y2)) -> if x1 = x2 then compare y1 y2 else compare x1 x2 let distance = function Point (x, y) -> sqrt (x *. x +. y *. y) let sort_by_dic = List.sort compare_point let sort_by_dis = List.sort (fun a b -> compare (distance a) (distance b))
実行結果,辞書順:
# sort_by_dic [Point (3.2, 1.9); Point (3.2, 0.3); Point (1.2, 3.5)];; - : point list = [Point (1.2, 3.5); Point (3.2, 0.3); Point (3.2, 1.9)]
距離の昇順:
# sort_by_dis [Point (3.2, 1.9); Point (3.2, 0.3); Point (1.2, 3.5)];; - : point list = [Point (3.2, 0.3); Point (1.2, 3.5); Point (3.2, 1.9)]