为什么在Prelude中有两个init函数定义?

时间:2019-03-15 13:00:15

标签: haskell

我在Prelude中发现了函数init的两个定义:

init [x] = []
init (x:xs) = x : init xs
init [] = errorEmptyList "init"

init [] = errorEmptyList "init"
init (x:xs) = init' x xs
  where init' _ [] = []
        init' y (z:zs) = y : init' z zs

第二个定义的原因是什么?

1 个答案:

答案 0 :(得分:12)

您没有逐字引用它。实际上是:

-- | Return all the elements of a list except the last one.
-- The list must be non-empty.
init                    :: [a] -> [a]
#if defined(USE_REPORT_PRELUDE)
init [x]                =  []
init (x:xs)             =  x : init xs
init []                 =  errorEmptyList "init"
#else
-- eliminate repeated cases
init []                 =  errorEmptyList "init"
init (x:xs)             =  init' x xs
  where init' _ []     = []
        init' y (z:zs) = y : init' z zs
#endif

USE_REPORT_PRELUDE意味着这段代码遵循Haskell Report,而另一段代码则可能是更有效的实现。请查看this thread,以了解关于reverse的类似讨论。

相关问题