Little Ball
Little Ball

Reputation: 5768

Returns the first element of a list in Haskell

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

Answers (2)

chepner
chepner

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

willeM_ Van Onsem
willeM_ Van Onsem

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 main = Main.head [1, 2, 3, 4, 5], since the type of a main is IO a with a an arbitrary type.

Upvotes: 5

Related Questions