haskell - 使用 typeclass 方法的默认实现来省略参数
问题描述
解决方案
The problem is in the default definition of specific
. Let's zoom out for a second and see what types your methods are actually given, based on your type signatures.
specific :: forall a b. MyType a b => b -> a -> a
dontCare :: forall a b. MyType a b => a -> a
In the default definition of specific
, you use dontCare
at type a -> a
. So GHC infers that the first type argument to dontCare
is a
. But nothing constrains its second type argument, so GHC has no way to select the correct instance dictionary to use for it. This is why you ended up needing AllowAmbiguousTypes
to get GHC to accept your type signature for dontCare
. The reason these "ambiguous" types are useful in modern GHC is that we have TypeApplications
to allow us to fix them. This definition works just fine:
class MyType a b where
specific :: b -> a -> a
specific = const (dontCare @_ @b)
dontCare :: a -> a
dontCare = specific (undefined :: b)
{-# MINIMAL specific | dontCare #-}
The type application specifies that the second argument is b
. You could fill in a
for the first argument, but GHC can actually figure that one out just fine.
推荐阅读
- jquery - 动态编写jquery脚本
- c# - 如何在不暂停代码的情况下在 PrintPreview 中打开 Excel 文件
- javascript - 如何仅在选择某个下拉菜单项时激活输入字段
- bootstrap-4 - Boostrap 4 中的 Flex 布局
- java - 如何在不丢失数据的情况下替换并发实例?
- c - 如何在同一台机器上以编程方式获取通过 AF_INET 套接字连接到我的代理的进程的 PID?
- codeigniter - 通过辅助函数在 codeigniter 中初始化第二个数据库
- javascript - create-react-app 中的 Google Calendar API gapi.client.init 抛出错误
- maven - Artifactory:上传的工件不再有 md5 和 sha1 文件
- python - 如何在python中保存相对于其id的坐标值