Search code examples
haskelllist-comprehensiontake

Implement the take function with list comprehension


How would you implement take with a list comprehension?

My approach so far:

take2 :: (Num i, Ord i) => i -> [a] -> [a]
take2 n xs = [x | x <- xs, [x..n]]

Solution

  • The fundamental reason why list comprehensions are not a good fit for the take function is this:

    The take function stops the evaluation of the argument list after n elements.

    But lists comprehensions always evaluate all elements of the list in the generator. There is no break-statement in Haskell.


    You can use some trick to truncate the list before or after using it in the list comprehension, but there is no real point of doing so. That would be similar to first using normal take to truncate the list, then using a list comprehension just to return the result.