代码之家  ›  专栏  ›  技术社区  ›  W.P. McNeill

如何对Haskell中的数据强制执行运行时条件?

  •  7
  • W.P. McNeill  · 技术社区  · 7 年前

    我想定义一个函数 f [Int] -> Int 哪里 f

    在命令式语言中,我会添加一行 assert sqrt(len(xs)) is integer

    我更希望程序在未定义的情况下因错误而停止,而不是让函数返回 Nothing .

    2 回复  |  直到 7 年前
        1
  •  9
  •   luqui    7 年前

    如果你想正式一点的话,这可能是一个使用 smart constructor .

    module PSqList
        ( PSqList   -- constructor *not* exported
        , fromList
        )
    where
    
    newtype PSqList a = PSqList [a]
        deriving (Functor, Foldable)
    
    fromList :: [a] -> Maybe (PSqList a)
    fromList xs
        | isPerfectSquare (length xs) = Just (PSqList xs)
        | otherwise = Nothing
    

    那么当你使用 PSqList PSqList

    用一个完整的模块来做这样的事情感觉有点奇怪;也许你需要一个更通用的不变跟踪系统。这是一个依赖类型语言(如Agda)的领域,但Haskell中有一个可爱的中点,如功能表所示 Ghosts of Departed Proofs .

        2
  •  5
  •   jberryman    7 年前

    我更喜欢在未定义的情况下让程序带错误停止,而不是让函数什么都不返回。

    实现这一点的标准和惯用方法当然是返回 Maybe Int ,而不是做你说你更喜欢做的事。

    如果您询问如何从纯代码引发错误,您可以这样做

    f ... = error "oops it wasn't a perfect square"
    

    另一种可能是,您的输入 [Int] PowerOfTwoList a

    推荐文章