检查haskell中函数参数的最佳方法

时间:2013-11-08 22:47:34

标签: function haskell arguments

我有一个功能说foo :: [Integer] - > Bool,但它仅在传入参数对某些条件有效时才有效,否则应立即终止。

 foo x | not $ isSorted x = False
       | otherwise = some_recursive_stuff_here
       where
            isSorted ax = ax == sort ax

但是我不希望每次都检查不变量是否排序。是否有一种很好的方法可以处理另一种其他内部函数?

1 个答案:

答案 0 :(得分:21)

您可以通过创建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