将类型签名指定为变量

时间:2016-05-17 15:02:00

标签: haskell

假设我有一个排序算法和两个自定义比较器:

mySort :: [[Int]] -> ([Int] -> [Int] -> Ordering) -> [[Int]]
mySort = undefined

myCmp1 :: [Int] -> [Int] -> Ordering
myCmp1 xs ys
  | a0 < b0 = LT
  | a0 > b0 = GT
  | a1 < b1 = LT
  | a1 > b1 = GT
  | a1 == b1 = EQ where
    a0 = head xs
    b0 = head ys
    a1 = last xs
    b1 = last ys

myCmp2 :: [Int] -> [Int] -> Ordering
myCmp2 xs ys
  | a0 > b0 = LT
  | a0 < b0 = GT
  | a1 > b1 = LT
  | a1 < b1 = GT
  | a1 == b1 = EQ where
    a0 = head xs
    b0 = head ys
    a1 = last xs
    b1 = last ys

有没有办法定义类型签名[Int] -> [Int] -> Ordering,以便我可以像这样使用它?

comparator = [Int] -> [Int] -> Ordering

mySort :: [[Int]] -> comparator -> [[Int]]
mySort = undefined

1 个答案:

答案 0 :(得分:12)

这是别名的类型:

type Comparator = [Int] -> [Int] -> Ordering

他们也可以参数:

type Comparator a = a -> a -> Ordering

然后你可以写,例如

mySort :: Comparator a -> [a] -> [a]