haskell - 如何在 Haskell 中打印列表的最后一个元素?
问题描述
我正在从这里做一些 Haskell 练习:https ://wiki.haskell.org/99_questions/Solutions/1它显示了解决方案,但没有显示如何打印结果
我试过了
myLast :: [a] -> IO ()
myLast [] = error "No end for empty lists!"
myLast [x] = print x
myLast (_:xs) = myLast xs
main :: IO ()
main = myLast [1,2,3]
我有
/workspaces/hask_exercises/exercises/src/Lib.hs:10:14: error:
* No instance for (Show a) arising from a use of `print'
Possible fix:
add (Show a) to the context of
the type signature for:
myLast :: forall a. [a] -> IO ()
* In the expression: print x
In an equation for `myLast': myLast [x] = print x
如何打印最后一个元素?
我认为列表中元素的类型必须以某种方式实现Show
,但我不知道如何强制执行。
解决方案
要求列表元素所属的方法Show
是将该约束添加到类型签名中:
myLast :: Show a => [a] -> IO ()
推荐阅读
- java - 无法为根项目设置未知属性“mainClassName”
- reactjs - 创建动态按需输入字段
- c++ - 为什么我的程序的输出不断变化?EAX寄存器不断变化的值?
- c# - 如何在 v5 中为 Swagger 定义相对路径?
- c# - JPEG 位图元数据保存失败,EXIF 缩略图较大
- python - 有没有办法计算 make_blob 生成的数据集的 cluster_std?
- cron - 为什么我的 crontab 不能使用 /etc/crontab 文件
- maven - Java 二进制文件的 Sonarqube 无效值
- nginx - 上游在访问 https 域时从上游读取响应标头时未发送有效的 HTTP/1.0 标头
- mysql - 我知道 PIVOT 命令可以转换数据集,这是正确的方法吗?