您可以通过创建一个newtype
.
newtype Sorted a = Sorted { fromSorted :: [a] }
sorted :: Ord a => [a] -> Sorted a
sorted = Sorted . sort
foo :: Sorted Integer -> Bool
foo (Sorted as) -> some_recursive_stuff_here
如果您将Sorted
构造函数隐藏在单独的模块中,那么您的代码的用户将无法使用foo
,除非先创建排序证明。他们也无法做到,sort
因此Sorted
您可以确定它只发生过一次。
如果您愿意,您甚至可以支持证明维护操作。
instance Monoid (Sorted a) where
mempty = Sorted mempty
mappend (Sorted as) (Sorted bs) = Sorted (go as bs) where
-- lazy stable sort
go :: Ord a => [a] -> [a] -> [a]
go [] xs = xs
go xs [] = xs
go (x:xs) (y:ys) | x == y = x : y : go xs ys
| x < y = x : go xs (y:ys)
| x > y = y : go (x:xs) ys
(此代码现在在 Hackage 上可用:http: //hackage.haskell.org/package/sorted)