2016-05-17 20 views
6

Diciamo che ho un algoritmo di ordinamento e due comparatori personalizzati:Assegnazione tipo di firma come variabile

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 

C'è un modo per definire il tipo di firma [Int] -> [Int] -> Ordering modo che posso usare in questo modo?

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

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

dato il tipo di 'myCmp1', il tipo di' mySort' sembra un po 'strano - sei sicuro che l'ingresso e l'uscita dovrebbe essere '[Int]' piuttosto che '[[Int]]'? –

+0

Grazie, risolto. Facile da perdere quando si costruisce un esempio generico. – tsorn

risposta

12

Questo è ciò che gli alias Tipo fare:

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

Essi possono anche prendere argomenti:

type Comparator a = a -> a -> Ordering 

Poi si potrebbe scrivere, per esempio

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