Reputation: 5768
How do I return the first element of a list in haskell?
I'm using https://www.tutorialspoint.com/compile_haskell_online.php to compile my code.
This is what I have so far.
main = head ([1, 2, 3, 4, 5])
head :: [a] -> a
head [] = error "runtime"
head (x:xs) = x
It's giving me the following error:
$ghc -O2 --make *.hs -o main -threaded -rtsopts
[1 of 1] Compiling Main ( main.hs, main.o )
main.hs:1:8: error:
Ambiguous occurrence ‘head’
It could refer to either ‘Prelude.head’,
imported from ‘Prelude’ at main.hs:1:1
(and originally defined in ‘GHC.List’)
or ‘Main.head’, defined at main.hs:4:1
Upvotes: 2
Views: 1591
Reputation: 530833
You can explicitly import Prelude
without head
, preventing the name clash with your version.
import Prelude hiding (head)
head :: [a] -> a
head [] = error "runtime"
head (x:xs) = x
main = print $ head [1, 2, 3, 4, 5]
Upvotes: 3
Reputation: 476503
the problem is that head [1,2,3,4,5]
can refer both to the head
you defined or the one implemented from the Prelude
.
You can disambiguate by specifying the module:
module Main where
main = print (Main.head [1, 2, 3, 4, 5])
You can furthermore not use , since the type of a main = Main.head [1, 2, 3, 4, 5]
main
is IO a
with a
an arbitrary type.
Upvotes: 5