[Haskell-cafe] Ultra-newbie Question
Alexander Solla
ajs at 2piix.com
Sat Sep 18 17:29:40 EDT 2010
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100918/0d61e535/attachment.html
More information about the Haskell-Cafe
mailing list