使用OCaml标准库函数对列表进行排序 [英] Sorting List with OCaml standard library function

查看:120
本文介绍了使用OCaml标准库函数对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习OCaml,并在订购数据时进行各种练习。
我想了解如何使用标准库管理器列表进行排序

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

例如,我想用这些函数对这个数组进行排序[94; 50; 6; 7; 8; 8]

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 ?

推荐答案

如果您想在列表中使用这些函数,您必须指定比较函数。

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



Quote from the documentation:


比较函数必须返回0,如果它的参数比较为
equal,则返回一个正整数,如果第一个比较大,如果第一个更小,则为负
整数

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

在模块 Pervasives 你有一个多态的比较函数:

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]

这篇关于使用OCaml标准库函数对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆