Haskell编译器可以对使用"undefined"的函数发出警告

Leo*_*ang 11 haskell

如果我使用"undefined"这样定义一个函数,它会进行类型检查.

add2 :: Int -> Int -> Int
add2 = undefined
Run Code Online (Sandbox Code Playgroud)

是否可以检测函数定义中是否有任何函数使用"未定义",并将其转换为警告?

在开发阶段,我可以使用"undefined"在我实现函数之前检查类型签名是否正确.然后在制作中我可以有一些方法来捕捉我忘记为"未定义"的函数实现的错误.

Ale*_*ing 21

一个好的解决方案是使用类型化的孔,而不是undefined随着-fdefer-typed-holes编译器标志,使他们的警告,而不是错误(这一般是比较有用的,反正).启用此标志后,您可以像这样编写示例:

add2 :: Int -> Int -> Int
add2 = _
Run Code Online (Sandbox Code Playgroud)

...产生以下警告:

warning: [-Wtyped-holes]
    • Found hole: _ :: Int -> Int -> Int
    • In the expression: _
      In an equation for ‘add2’: add2 = _
    • Relevant bindings include
        add2 :: Int -> Int -> Int
Run Code Online (Sandbox Code Playgroud)

现代GHC甚至会在警告中包含一个可能的替换列表:

      Valid substitutions include
        add2 :: Int -> Int -> Int
        (+) :: forall a. Num a => a -> a -> a
          (imported from ‘Prelude’ (and originally defined in ‘GHC.Num’))
        (*) :: forall a. Num a => a -> a -> a
          (imported from ‘Prelude’ (and originally defined in ‘GHC.Num’))
        (^) :: forall a b. (Num a, Integral b) => a -> b -> a
          (imported from ‘Prelude’ (and originally defined in ‘GHC.Real’))
        (-) :: forall a. Num a => a -> a -> a
          (imported from ‘Prelude’ (and originally defined in ‘GHC.Num’))
        seq :: forall a b. a -> b -> b
          (imported from ‘Prelude’ (and originally defined in ‘GHC.Prim’))
        (Some substitutions suppressed; use -fmax-valid-substitutions=N or -fno-max-valid-substitutions)
Run Code Online (Sandbox Code Playgroud)