gpt4 book ai didi

haskell - 将类型签名分配为变量

转载 作者:行者123 更新时间:2023-12-04 13:37:34 27 4
gpt4 key购买 nike

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

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

最佳答案

这就是类型别名的作用:

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

他们也可以接受论点:
type Comparator a = a -> a -> Ordering

然后你可以写,例如
mySort :: Comparator a -> [a] -> [a]

关于haskell - 将类型签名分配为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37279777/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com