我在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
Run Code Online (Sandbox Code Playgroud)
第二个定义的原因是什么?
Bar*_*icz 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
Run Code Online (Sandbox Code Playgroud)
这USE_REPORT_PRELUDE意味着这段代码符合Haskell Report,而另一段则可能是更有效的实现。请查看此主题,以获取有关的类似讨论reverse。