首页 > 解决方案 > 返回 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

标签: haskell

解决方案


问题在于,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],因为 a 的类型是main任意类型。IO aa


推荐阅读