[Haskell-cafe] Newbie question

Tom Ellis tom-lists-haskell-cafe-2017 at jaguarpaw.co.uk
Sat Jan 15 14:56:29 UTC 2022


On Sat, Jan 15, 2022 at 09:32:27AM -0500, Terry Phelps wrote:
> last [] = []
> (Yes, I know that's not a non-empty list, but I don't want ghci whining
> about non-exhaustive patterns). Then I added:
> 
> last [x] = x
> And I checked the type:
> :t last
> last:: [a] -> [a]
> 
> Yes, that looks right. There seems to be only one other case: 2 or more
> elements. So I wrote:
> 
> last (x:y:xs) = last (y:xs)

The first problem is that you've defined three different functions,
each overriding the next

Prelude> foo s = "Hello " ++ s
Prelude> foo s = "Goodbye " ++ s
Prelude> foo "Tom"
"Goodbye Tom"


I suggest putting the functions in a source file, say "test.hs" and
then loading it in GHCi instead.  I also suggest calling your function
"mylast" because Prelude already exports a function called "last":

% cat test.hs  
mylast [] = []
mylast [x] = x
mylast (x:y:xs) = mylast (y:xs)
% ghci         
...
Prelude> :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, one module loaded.
*Main> :t mylast
mylast :: [[a]] -> [a]
*Main> mylast [[1,2], [3,4]]
[3,4]


It kind of does what you want, but not quite.  That's the next problem
for you to solve!  Good luck and enjoy.

Tom


More information about the Haskell-Cafe mailing list