GHC splitAt performance

splitAt is implemented in the GHC as follows:

splitAt n xs = (take n xs, drop n xs) 
  • So, does splitAt do a double job or are there some behind curtain optimization?
  • In addition, take and drop generates a recursive process. Why is this. After all, they are library functions, and beauty is not so important. Why aren't they designed to create an iterative process?
+6
source share
2 answers

The definition you are looking for is the Haskell Report Definition of Prelude.

Quote from this page (emphasis mine)

This chapter gives all of Haskell's prelude. It is a specification of the Prelude. Many of the definitions are written with clarity, and not in terms of efficiency, and the specification is not required to be implemented, as shown here.

So, in the GHC source, when you see

 #ifdef USE_REPORT_PRELUDE // Haskell report prelude definition here (inefficient) #else // Efficient definition here #endif 

you should read the #else branch if you want to see a definition that will usually be used unless you specifically request a Haskell report definition.

+14
source

As for your second question, a recursive process is usually what you want when dealing with lists, because they are a data structure with hollows. Consider the following code:

head (take 100 [1 ..])

If we follow the code, we will eventually arrive at the following expression: 1 : take (100 - 1) [2 ..] . Since we are only interested in the head of the list, the recursive call to take never evaluated. However, if take was to be implemented as an iterative process, it would need to iterate over all 100 elements, even if only the first element was needed.

+2
source

Source: https://habr.com/ru/post/959458/


All Articles