On Sep 18, 2010, at 12:51 AM, Christopher Tauss wrote:


I am a professional programmer with 11 years experience, yet I just do not seem to be able to get the hang of even simple things in Haskell. I am trying to write a function that takes a list and returns the last n elements.


Note that keeping just the suffix is the same as dropping the prefix. Consider your data:

A finite list.
The length of the suffix to keep.
An algebraic relationship between lengths of lists, suffixes, and their prefixes:

length(prefix) + length(suffix) = legnth(list)

Putting all of this together:

n_tail n list = drop (prefix_length) list where
        prefix_length = length list - n

You may be interested in how drop is carrying around some state:

drop n xs     | n <= 0 =  xs
drop _ []              =  []
drop n (_:xs)          =  drop (n-1) xs

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to