2015-12-01 158 views
0

我正在遞歸的Haskell中創建合併排序函數。有人告訴我,我的評估的一部分,我必須定義類型爲:Haskell - Ord類型是什麼意思?

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] 
... 
+0

嘗試在最後三行上重命名'a'? – Jacob

+1

這裏沒有陣列。 '[a]'是一個* list *類型。 – dfeuer

回答

6

Ord a是一個類型類的約束,表示你的函數適用於任何類型a,只要a是可比的(Ord erable)。您收到的錯誤消息是由於您的外部聲明(表示其適用於任何Ord a => a)和內部insert(僅「適用於Int」)之間的衝突。

+0

什麼是內部聲明的解決方案? – nonsequiter

+0

@nonsequiter我希望你可以刪除'insert'類型聲明並且推斷它。如果你想明確地指定它,你需要保持一致。 'isort'被聲明爲*任何/每個*'a'的工作是可比的,但是'insert'被聲明爲僅適用於'Int',這是一種特定的可比類型。 'Ord a => a - > [a] - > [a]'可以工作。 – ryachza

+0

@nonsequiter此外,它看起來有一個bug,因爲'insert'的基本情況下'a'(變量,而不是類型)被忽略,應該可能是'a:[]'。 – ryachza