[Haskell-beginners] my own last function
toad3k at gmail.com
Sat Feb 18 19:37:14 CET 2012
[a] when used as an argument doesn't mean what you think it does. It
means a list with only one element a. So your function will only
match one single case, a list such as , or a string with one
Here are all the things you could match on:
xs -> just a variable which will contain the whole list
 -> an empty list
[a] -> a list with one element in it, which you can reference via a
[a,b,c] -> a list with exactly three elements in it, which can all be referenced
(x:xs) -> a list with at least one element, of which x is that
element, and xs is the rest of the list
(x:) -> a list with one element, followed by nothing else.
Essentially the same as [x].
(x:y:xs) -> a list with two elements, xs has the rest of the list.
Remember that xs could be empty.
So think about the problem. If someone passes in a list, it either
has one element, or it has more than one and we want to get to the
last :: [x] -> x
last [x] = x
Well that deals with the easy case. One element, one answer. But if
there is more than one element, then what?
last (_:xs) = last xs
Just discard the first one and run the function again on what remains.
On Sat, Feb 18, 2012 at 1:18 PM, bahadýr altan <doaltan at yahoo.co.uk> wrote:
> Hello everyone, I have just started studying and started trying to solve 99
> questions in haskell.org. However I got stuck even in the first question.
> The first question wants me to write my own last function and I wrote this
> q1mylast :: [x] -> x
> q1mylast [a] = if length [a] <=1 then a
> else q1mylast (tail [a])
> This program doesn't work and it gives this error :
> Program error: pattern match failure: q1mylast "doaltan"
> I'll be very glad if you could tell me what's wrong with the code and how
> can I fix it..
> Thanks in advance :)
> Beginners mailing list
> Beginners at haskell.org
More information about the Beginners