Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning type signature as variable

Tags:

haskell

Let's say I have a sorting algorithm and two custom comparators:

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

Is there any way to define the type signature [Int] -> [Int] -> Ordering so that I can use it like this?

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

mySort :: [[Int]] -> comparator -> [[Int]]
mySort = undefined
like image 923
tsorn Avatar asked May 17 '16 15:05

tsorn


1 Answers

This is what type aliases do:

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

They can also take arguments:

type Comparator a = a -> a -> Ordering

Then you could write, e.g.

mySort :: Comparator a -> [a] -> [a]
like image 126
Daniel Wagner Avatar answered Sep 17 '22 18:09

Daniel Wagner