Haskell - Ord的意思是什么?

时间:2015-12-01 15:11:47

标签: haskell types

我在Haskell中创建一个递归的合并排序函数。作为评估的一部分,我被告知必须将类型定义为:

isort :: Ord a => [a] -> [a]

我假设函数需要一个数组作为输入并输出一个数组。我知道ord是一个班级。

在上面的上下文中Ord a是什么意思?

这是我的功能:

isort :: Ord a => [a] -> [a]
isort [x] = [x]
isort (x:xs) = insert x (isort xs)
    where
        insert :: Int -> [Int] -> [Int]
        insert a [] = []
        insert a (b:c) | a < b      = a:b:c
                       | otherwise  = b : insert a c

当我尝试将我的函数文件加载到ghci时,我收到错误:

Couldn't match type ‘a’ with ‘Int’
  ‘a’ is a rigid type variable bound by
      the type signature for isort :: Ord a => [a] -> [a]
      at LabSheet2.hs:17:10
Expected type: [a]
Actual type: [Int]
...

1 个答案:

答案 0 :(得分:7)

Ord a是一个类型类约束,表示您的函数适用于任何类型a,只要a具有可比性(Ord erable)。您收到的错误消息是由于您的外部声明表明它适用于任何Ord a => a,以及内部insert“仅”适用于Int的内部class User { async void Foo() { var result = await GetMyTask().IgnoreCancelAndFailure(); ProcessResult(result); } } public static class TaskExtenstions { public static SilentTask<T> IgnoreCancelAndFailure<T>(this Task<T> task) { return new SilentTask<T>(task); } } public class SilentTask<T> { private readonly Task<T> _inner; public SilentTask(Task<T> inner) { _inner = inner; } public SilentAwaiter GetAwaiter() { return new SilentAwaiter(_inner); } public class SilentAwaiter : INotifyCompletion { private readonly TaskAwaiter<T> _inner; private readonly Task<T> _task; public SilentAwaiter(Task<T> task) { _task = task; _inner = task.GetAwaiter(); } public bool IsCompleted { get { return _task.Status == TaskStatus.RanToCompletion; } } public void OnCompleted(Action continuation) { _inner.OnCompleted(() => { if (IsCompleted) { continuation(); } }); } public T GetResult() { return _inner.GetResult(); } } }