Sorting List with OCaml standard library function

*爱你&永不变心* 提交于 2019-12-24 03:52:13

问题


I'm studying OCaml and and doing various exercises on ordering data. I would like to understand how to use the standard librari List for ordering

For example I would like to sort this array using these functions [94; 50; 6; 7; 8; 8]

List.sort 
List.stable_sort 
List.fast_sort 
List.unique_sort

What is the syntax to do it ?


回答1:


If you want to use these functions on your list, you have to specifiy the comparison function.

Quote from the documentation:

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

In the module Pervasives you have a polymorphic comparison function:

val compare : 'a -> 'a -> int

So, in your case you can just do:

List.sort compare [94; 50; 6; 7; 8; 8]


来源:https://stackoverflow.com/questions/26755939/sorting-list-with-ocaml-standard-library-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!