在Haskell中返回列表的第一个元素
如何在haskell中返回列表的第一个元素?
我正在使用https://www.tutorialspoint.com/compile_haskell_online.php来编译我的代码。
这是我到目前为止。
main = head ([1, 2, 3, 4, 5])
head :: [a] -> a
head [] = error "runtime"
head (x:xs) = x
它给了我以下错误:
$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
回答
问题是head [1,2,3,4,5]既可以指head您定义的,也可以指从Prelude.
您可以通过指定模块来消除歧义:
module Main where
main = print (Main.head [1, 2, 3, 4, 5])
您还可以不使用,因为的类型main = Main.head [1, 2, 3, 4, 5]main是IO a与a任意类型。