haskell - 返回 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])
您还可以不使用,因为 a 的类型是main = Main.head [1, 2, 3, 4, 5]
main
任意类型。IO a
a
推荐阅读
- python - 在 YAML 文件中读取配置值的适当方法
- c# - 像本地 json 文件一样从服务器读取 Json
- mysql - How to select win/loss record in mysql
- react-native - Get previously scene with react-native-router-flux
- javascript - moment(?).year(?).week(?).weekday(?).format('MM/DD/YYYY') 在 12 月不起作用
- android-studio - Kotlin 编译器构建错误 使用 -jvm-target 1.8 重新编译
- python - 在Python中解码某个bin文件
- swift - 如何修复 NSBezierPath 的便利 init w/closure Extension 以使用在 Swift 5.0 中失败的 CGPath?
- python - python read from text file line by line
- google-app-engine - 原生模式下的 Google Cloud Firestore 和 Recaptcha v3