<div dir="ltr"><div>I'm trying yet again to "get" Haskell. I'm reading Graham Hutton's book "Programming in Haskell", and am working on one of the exercises. Sounds easy enough:</div><div><br></div><div>Make a function 'last' that returns the last element of a non-empty list.</div><div><br></div><div>After struggling a while, I looked at the answer: last = head . reverse.</div><div>I wish I had thought of that. But I kept trying to get my recursive version done, but I can't seem to make ghci happy. (Version 8.10.5, if you care). I wrote:</div><div><br></div><div>last [] = [] <br></div><div>(Yes, I know that's not a non-empty list, but I don't want ghci whining about non-exhaustive patterns). Then I added:</div><div><br></div><div>last [x] = x</div><div>And I checked the type:</div><div>:t last</div><div>last:: [a] -> [a]</div><div><br></div><div>Yes, that looks right. There seems to be only one other case: 2 or more elements. So I wrote:</div><div><br></div><div>last (x:y:xs) = last (y:xs)</div><div><br></div><div>I ran it:</div><div><br></div><div>Prelude> last [1,2]<br>*** Exception: <interactive>:2:1-27: Non-exhaustive patterns in function last</div><div><br></div><div>What the heck is the problem? I've covered every possible list, haven't I?</div><div><br></div><div>Stranger yet, I check the type again:</div><div><br></div><div>Prelude> :t last<br>last :: [a] -> t</div><div><br></div><div>The type has changed. And I don't understand what it means. What's the 't'?</div><div><br></div><div>I'm sure this is a simple beginner error, but I'm really confused. I don't see how it isn't exhaustive, and I don't see why the 3rd clause (or whatever it's called) caused the type to change.</div><div><br></div><div>Someone help, please.<br></div></div>