I am learning Haskell and I come from an imperative programming language background.
I am trying to re implement some functions in the Data.List ghc library like head :
head :: [a] -> a
But when ran with an empty list it should throw an exception :
Prelude> head []
*** Exception: Prelude.head: empty list
This is fairly simple but I have this :
head :: [a] -> a
head [] = ??
head (x:xs) = x
How can I implement something similar in Haskell? I tried to look at the source code but it uses rather complicated structures and use a raise# function that I can’t find in the documentation.
The ambiguous type variable error is due to the fact that you are applying head to an emty list. This could be an empty list of any type. [] :: [Int] is an empty list of Int while []::[Char] is an empty list of Chars.
For the second question, error produces an exception and “returns” bottom, which is a special value that inhabits every type. I would suggest to read the first few paragraphs of this article.