I'm doing some Haskell exercises from here: https://wiki.haskell.org/99_questions/Solutions/1 where it shows the solution but it does not show how to print the result
I tried
myLast :: [a] -> IO ()
myLast [] = error "No end for empty lists!"
myLast [x] = print x
myLast (_:xs) = myLast xs
main :: IO ()
main = myLast [1,2,3]
I got
/workspaces/hask_exercises/exercises/src/Lib.hs:10:14: error:
* No instance for (Show a) arising from a use of `print'
Possible fix:
add (Show a) to the context of
the type signature for:
myLast :: forall a. [a] -> IO ()
* In the expression: print x
In an equation for `myLast': myLast [x] = print x
how can I print the last element?
I think somehow the type of the elements in the list must implement Show, but I don't know exactly how to force that.
The way to require that the list elements belong to
Showis to add that constraint to the type signature: